function person(pname, page) {
this.name = pname;
this.age = page;
}
person.prototype.profession = "football player";
var p1 = new person("Messi", 29);
var p2 = new person("Bale", 28);
console.log(p1.hasOwnProperty("name")); // true
console.log(p1.hasOwnProperty("hasOwnProperty")); //false
console.log(p1.__proto__ === person.prototype); //true
console.log(person.prototype.hasOwnProperty("hasOwnProperty")); //false
console.log(p1.__proto__.__proto__ === person.prototype.__proto__); //true
console.log(person.prototype.__proto__.hasOwnProperty("hasOwnProperty")); //true
解析:
function person(pname, page) {
this.name = pname;
this.age = page;
}
person.prototype.profession = "football player";
var p1 = new person("Messi", 29);
var p2 = new person("Bale", 28);//直接打印p1对象可知, p1包含自有属性name
console.log(p1.hasOwnProperty("name")); // true//同理,p1不包含函数hasOwnProperty, 改函数从原型链继承而来
console.log(p1.hasOwnProperty("hasOwnProperty")); //false//两种方式都可以原型对象, 因此为true
console.log(p1.__proto__ === person.prototype); //true//直接打印person.prototype可知, 原型对象不包含函数hasOwnProperty, 该函数从原型链继承而来
console.log(person.prototype.hasOwnProperty("hasOwnProperty")); //false//等价写法而已, 也可以等同于Object.prototype
console.log(p1.__proto__.__proto__ === person.prototype.__proto__); //true//person的原型是Object实例, 再往上就是Object原型, hasOwnProperty函数就保存在此对象上
console.log(person.prototype.__proto__.hasOwnProperty("hasOwnProperty")); //true
用一张图理清关系
![[图片]](https://i-blog.csdnimg.cn/blog_migrate/511cd1b7844465ad719de82228e0b7e1.png)

本文通过创建Person构造函数并设置其原型属性,演示了JavaScript中对象的原型链工作原理。详细解释了hasOwnProperty方法的来源及其在原型链上的传递过程。
1198

被折叠的 条评论
为什么被折叠?



