getPrototypeOf vs isPrototypeOf

时间:2018-02-06 00:21:31

标签: javascript

我正在阅读你不了解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):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?

1 个答案:

答案 0 :(得分:1)

逻辑在这里:

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只是在原型链中,而不是&#34; Direct&#34;原型。