Frank Yuan
Frank Yuan

Reputation: 131

getPrototypeOf vs isPrototypeOf

I'm reading You Don't Know JS, and confuse getPrototypeOf and isProtytypeOfs' result. 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):

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

Why the Foo.prototype.isPrototypeOf(a) is true but "Object.getPrototypeOf(a) === Foo.prototype" is false?

Upvotes: 0

Views: 191

Answers (1)

xianshenglu
xianshenglu

Reputation: 5369

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.

Upvotes: 1

Related Questions