[英]getPrototypeOf vs isPrototypeOf
I'm reading You Don't Know JS , and confuse getPrototypeOf and isProtytypeOfs' result. 我正在阅读“ 您不知道JS” ,并且混淆了getPrototypeOf和isProtytypeOfs的结果。 Code like below: 如下代码:
<html>
<script>
function Foo(name) {
this.name = name;
};
Foo.prototype.myName = function() {
return this.name;
};
function Bar(name, label) {
Foo.call(this, name);
this.label = label;
};
Bar.prototype = Object.create(Foo.prototype);
Bar.prototype.myLabel = function() {
return this.label;
};
var a = new Bar("a", "obj a");
console.log("getPrototypeOf:", Object.getPrototypeOf(a));
console.log("Foo.prototype.isPrototypeOf(a):", Foo.prototype.isPrototypeOf(a));
console.log("Object.getPrototypeOf(a) === Foo.prototype:", Object.getPrototypeOf(a) === Foo.prototype);
console.log("Bar.prototype.isPrototypeOf(a):", Bar.prototype.isPrototypeOf(a));
console.log("Object.getPrototypeOf(a) === Bar.prototype:", Object.getPrototypeOf(a) === Bar.prototype);
</script>
The result like below(chrome 64): 结果如下(chrome 64):
getPrototypeOf: Foo {myLabel: ƒ} getPrototypeOf:Foo {myLabel:ƒ}
Foo.prototype.isPrototypeOf(a): true Foo.prototype.isPrototypeOf(a):是
Object.getPrototypeOf(a) === Foo.prototype: false Object.getPrototypeOf(a)=== Foo.prototype:否
Bar.prototype.isPrototypeOf(a): true Bar.prototype.isPrototypeOf(a):是
Object.getPrototypeOf(a) === Bar.prototype: true Object.getPrototypeOf(a)=== Bar.prototype:true
Why the Foo.prototype.isPrototypeOf(a) is true but "Object.getPrototypeOf(a) === Foo.prototype" is false? 为什么Foo.prototype.isPrototypeOf(a)为true,而“ Object.getPrototypeOf(a)=== Foo.prototype”为假?
logic is here: 逻辑在这里:
console.log(a instanceof Bar);//true
console.log(Object.getPrototypeOf(a));//Foo { myLabel: [Function] }
console.log(Object.getPrototypeOf(a) instanceof Foo);//true
console.log(Object.getPrototypeOf(Object.getPrototypeOf(a))===Foo.prototype);//true
actually,you can change the code : 实际上,您可以更改代码:
Bar.prototype = Object.create(Foo.prototype);
to 至
Bar.prototype = new Foo();
the result is still the same.May it will be easier to understand though there is a little different between two ways. 结果仍然是相同的。尽管两种方法之间有些许差异,但可能会更容易理解。
just as @Bergi said, Foo.prototype is just in the a's prototype chain but not the "Direct" prototype. 就像@Bergi所说的那样,Foo.prototype只是在a的原型链中,而不是在“ Direct”原型中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.