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