zl程序教程

您现在的位置是:首页 >  后端

当前栏目

js中prototype的用法「建议收藏」

JS 建议 收藏 用法 prototype
2023-06-13 09:12:39 时间

大家好,又见面了,我是你们的朋友全栈君。

看例子就懂了

例1

可以在外部使用prototype为自定义的类型添加属性和方法

<script type="text/javascript">   
function Aclass()   
{   
this.Property = 1;   
this.Method = function()   
{   
    alert(1);   
}   
}   
Aclass.prototype.Property2 = 2;   
Aclass.prototype.Method2 = function  
{   
    alert(2);   
}   
var obj = new Aclass();   
alert(obj.Property2);   
obj.Method2();   
</script>   

例2

如何让一个类型继承于另一个类型

<script type="text/javascript">   
function AClass()   
{   
       this.Property = 1;   
       this.Method = function()   
       {   
              alert(1);   
       }   
}   

function AClass2()   
{   
       this.Property2 = 2;   
       this.Method2 = function()   
       {   
              alert(2);   
       }   
}   
AClass2.prototype = new AClass();   

var obj = new AClass2();   
alert(obj.Property);   
obj.Method();   
alert(obj.Property2);   
obj.Method2();   
</script>   

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/163362.html原文链接:https://javaforall.cn