javascript关于使用prototype给对象添加函数

来源:互联网 发布:mac英雄联盟美服网站 编辑:程序博客网 时间:2024/06/06 09:01


首先,常见的为对象添加函数的代码如下:

function Person(){this.name="ljx";  this.age=20;this.show=function(){document.write("我的名字是:"+this.name);}}  var p1=new Person();var p2=new Person();document.write(p1.show==p2.show);  //false 说明两个对象的函数都各自占用一份内存   等号判断的是地址(对象函数的地址)

使用prototype给对象添加函数的代码如下:

function Person(){this.name="ljx"; this.age=20;}  function display(){document.write("我的名字是:"+this.name);}Person.prototype.show=display;var p1=new Person();var p2=new Person();document.write(p1.show==p2.show);//true 此时这个函数使共享的,仅暂用一份内存

注明:如果等号两边是对象或者对象的函数,则比较地址是否相等(即判断两者是否引用的同一对象)

所以,我觉得第二个方法给对象添加函数比第一个好

 

特别说明:使用prototype添加的函数,不能调用私有变量和函数

function Person(name1,age1){this.name=name1;var age=age1;}Person.prototype.show=function(){document.write("名字:"+this.name); //这样是没问题的}var p3=new Person('ljx',20);p3.show();//若把上面代码改为如下,则报错Person.prototype.show=function(){document.write("名字:"+this.name+" 年龄:"+this.age); //这样是错误的 }var p3=new Person('ljx',20);p3.show();  //age输出undefined



 



0 0
原创粉丝点击