Javascript getPrototypeOf vs isPrototypeOf
我读到你不知道JS,混淆了getPrototypeOf和IsPrototypeOf的结果。代码如下:Javascript getPrototypeOf vs isPrototypeOf,javascript,Javascript,我读到你不知道JS,混淆了getPrototypeOf和IsPrototypeOf的结果。代码如下: <html> <script> function Foo(name) { this.name = name; }; Foo.prototype.myName = function() { return this.name; }; function Bar(name, label) {
<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>
函数Foo(名称){
this.name=名称;
};
Foo.prototype.myName=函数(){
返回此.name;
};
功能栏(名称、标签){
Foo.call(这个,名字);
this.label=标签;
};
Bar.prototype=Object.create(Foo.prototype);
Bar.prototype.myLabel=函数(){
返回此.label;
};
var a=新条形(“a”、“obj a”);
log(“getPrototypeOf:”,Object.getPrototypeOf(a));
log(“Foo.prototype.isPrototypeOf(a):”,Foo.prototype.isPrototypeOf(a));
log(“Object.getPrototypeOf(a)==Foo.prototype:”,Object.getPrototypeOf(a)==Foo.prototype);
log(“Bar.prototype.isPrototypeOf(a):”,Bar.prototype.isPrototypeOf(a));
log(“Object.getPrototypeOf(a)==Bar.prototype:”,Object.getPrototypeOf(a)==Bar.prototype);
结果如下(chrome 64):
getPrototypeOf:Foo{myLabel:ƒ}
Foo.prototype.isPrototypeOf(a):true
Object.getPrototypeOf(a)==Foo.prototype:false
Bar.prototype.isPrototypeOf(a):true
Object.getPrototypeOf(a)==Bar.prototype:true
为什么Foo.prototype.isPrototypeOf(a)为true而“Object.getPrototypeOf(a)==Foo.prototype”为false?逻辑如下:
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
实际上,您可以更改代码:
Bar.prototype = Object.create(Foo.prototype);
到
结果仍然是一样的。虽然两种方法有点不同,但可能更容易理解
正如@Bergi所说,Foo.prototype只是在a的prototype链中,而不是“直接”prototype。因为
a
的prototype是Foo.prototype
的一个实例,而不是Foo.prototype
本身。因为isPrototypeOf
是可传递的。@Bergi能给我一些细节吗?谢谢它在原型链的任何地方检查原型,它不是isDirectPrototypeOf
@Bergi感谢您的反馈!正如Bergi所说,Foo.prototype只是在a的原型链中,而不是“直接”原型?谢谢你的回答!
Bar.prototype = new Foo();