繁体   English   中英

getPrototypeOf与isPrototypeOf

[英]getPrototypeOf vs isPrototypeOf

我正在阅读“ 您不知道JS” ,并且混淆了getPrototypeOf和isProtytypeOfs的结果。 如下代码:

<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>

结果如下(chrome 64):

getPrototypeOf:Foo {myLabel:ƒ}

Foo.prototype.isPrototypeOf(a):是

Object.getPrototypeOf(a)=== Foo.prototype:否

Bar.prototype.isPrototypeOf(a):是

Object.getPrototypeOf(a)=== Bar.prototype:true

为什么Foo.prototype.isPrototypeOf(a)为true,而“ Object.getPrototypeOf(a)=== Foo.prototype”为假?

逻辑在这里:

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);

Bar.prototype = new Foo();

结果仍然是相同的。尽管两种方法之间有些许差异,但可能会更容易理解。

就像@Bergi所说的那样,Foo.prototype只是在a的原型链中,而不是在“ Direct”原型中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM