Javascript .isPrototypeOf()和.hasOwnProperty()方法混淆
假设我有这个代码:Javascript .isPrototypeOf()和.hasOwnProperty()方法混淆,javascript,Javascript,假设我有这个代码: //男性将继承所有人类财产 功能人(x,y){ //将继承以下属性 this.name=x; 这个年龄=y; this.test=“test 1”; } //以下属性也将被继承 Human.prototype.citizen=“美国”; Human.prototype.employer=“谷歌”; Human.prototype.test=“测试2”; 功能外螺纹(x,y){ //以下属性将是男性实例的自身属性 this.name=x; 这个年龄=y; this.gende
//男性将继承所有人类财产
功能人(x,y){
//将继承以下属性
this.name=x;
这个年龄=y;
this.test=“test 1”;
}
//以下属性也将被继承
Human.prototype.citizen=“美国”;
Human.prototype.employer=“谷歌”;
Human.prototype.test=“测试2”;
功能外螺纹(x,y){
//以下属性将是男性实例的自身属性
this.name=x;
这个年龄=y;
this.gender=“男”;
}
//继承-连接男性对象和人类对象
Male.prototype=新人类();//不传递任何参数
Male.prototype.constructor=Male;//更正构造函数属性
var albert=新男性(“albert”,25岁)代码>人类
功能不在阿尔伯特的原型链中。Human.prototype
引用的对象是:
Human.prototype.isPrototypeOf(albert); // true
人类。拥有自己的财产(“年龄”);///我希望它会回到现实
Human
函数没有age
属性。通过new
do创建的实例:
new Human().hasOwnProperty("age"); // true
旁注:您设置继承链的方式很常见,并在许多示例中显示,但在两个方面不正确:
新人类
创建男性原型
Male
呼叫Human
:新人类
为男性
创建原型的原因很简单:人类
需要参数,但您没有任何参数
以下是该代码的更新ES5和早期版本:
function-Human(name,age){//参数名称应该有意义
this.name=名称;
这个。年龄=年龄;
this.test=“test 1”;
}
Human.prototype.citizen=“美国”;
Human.prototype.employer=“谷歌”;
Human.prototype.test=“测试2”;
功能男性(姓名、年龄){
人类。称呼(这个、名字、年龄);
this.gender=“男”;
}
Male.prototype=Object.create(Human.prototype);
Male.prototype.constructor=Male;
var albert=新男性(“albert”,25岁);
console.log(Human.prototype.isPrototypeOf(albert));//真的
console.log(new Human().hasOwnProperty(“age”);//true
每个问题可能重复一个问题,但您从未定义任何Human.age
,因此应为false(您正在Human
实例上设置.age
)。对于第二个问题,如果Human.hasOwnProperty(“age”)
不起作用,因为它不是实例,为什么Male.hasOwnProperty(“name”)
将返回true
,而Male.hasOwnProperty(“age”)
将返回false
?@xcode:因为从ES2015(也称为“ES6”)开始,函数具有name
属性。如果你看Male.name
,你会看到它是“Male”
。同样对于noteHuman.hasOwnProperty(“name”)
将返回true
,那么这里发生了什么?我真的很想了解这个链条是如何工作的。感谢you@xcode:同样,函数具有名称
属性Human.name
将是“Human”
@xcode:我将添加一个快速图表,我认为它可能会有所帮助。
function Male(x, y) {
// Give Human its chance to initialize the object (#2)
Human.call(this, x, y);
// ...
}
// Don't use new Human to create the prototype (#1)
Male.prototype = Object.create(Human.prototype);
Male.prototype.constructor = Male;