js属性具体存在位置(实例/原型)

来源:互联网 发布:全境封锁 网络优化 编辑:程序博客网 时间:2024/06/06 13:58

1 hasOwnProperty()方法用来判断该属性是否存在于实例中。in操作符为属性存在于实例或原型中均正确。

function Person(){

 Person.prototype.name="Nicholas";

Person.prototype.age=29;

Person.prototype.job="software Engineer";

Person.prototype.sayName=function(){

  alert(this.name);

 }

}

var person1=new Person();

var person2=new Person();


alert(person1.hasOwnProperty("name"));//false    因此时,person1中没有实例为name的属性。

alert("name' in person1);//true   person1中存在属性name


person1.name="Greg';

alert(person1.name);//Greg

alert(person1.hasOwnProperty("name"));//true    因此时,person1中有实例为name的属性。

alert("name' in person1);//true   person1中存在属性name

故可以书写实现有原型属性的方法:

function hasPrototypeProperty(object,name){

 return !object.hasOwnProperty(name)&&(name in object);

}

注:isPrototyeOf()方法来确定对象之间是否存在这种关系。

alert(Person.prototype.isPrototypeOf(person1));//true;

alert(Person.prototype.isPrototyoeOf(person2));//ture

 

0 0
原创粉丝点击