js 判断存在于原型中的属性

来源:互联网 发布:php 开源网盘 编辑:程序博客网 时间:2024/05/17 01:53
<!DOCTYPE html><html><head>    <title></title></head><script>    function Person() {    }    Person.prototype.name="Nicholas";    Person.prototype.age=29;    Person.prototype.sayName=function(){        alert(this.name);    }    var person1=new Person();    person1.name="Greg";    var person2=new Person();console.log(person1.hasOwnProperty("name"));//trueconsole.log(person2.hasOwnProperty("name"));//falseconsole.log("name" in person1);//trueconsole.log("name" in person2);//truefor (var prop in person1) {    console.log(prop);//name   age   sayName}function hasPrototypeProperty(object,pro) {//如此可判断存在于原型中的属性    return (!object.hasOwnProperty(pro))&&(pro in object);}console.log(hasPrototypeProperty(person1,"name"));//falseconsole.log(hasPrototypeProperty(person2,"name"));//true</script><body></body></html>
0 0
原创粉丝点击