混淆"instanceof"结果

sof*_*sof 5 javascript

    function Foo() {}

    function Bar() {}

    Bar.prototype = new Foo()

    console.log("Bar.prototype.constructor === Foo ? " 
     + (Bar.prototype.constructor === Foo))

    console.log("new Bar() instanceof Bar? " 
     + (new Bar() instanceof Bar))
Run Code Online (Sandbox Code Playgroud)
=> Bar.prototype.constructor === Foo ? true
=> new Bar() instanceof Bar? true
Run Code Online (Sandbox Code Playgroud)

为什么"instanceof"结果不是"假",因为"构造函数"不是指自己而是继承原型?

Fel*_*ing 6

instanceof不使用该constructor财产.它在内部调用[HasInstance]函数对象的方法,该方法在规范的§15.3.5.3中描述.

它将对象的原型(以及对象原型的原型等)与prototype函数的属性进行比较.

类似的实现将是:

function myInstanceOf(obj, Constr) {
    // get prototype of object
    var proto = Object.getPrototypeOf(obj);

    // climb up the prototype chain as long as we don't have a match
    while (proto !==  Constr.prototype && proto !== null) {
        proto = Object.getPrototypeOf(proto);
    }

    return proto === Constr.prototype;
}
Run Code Online (Sandbox Code Playgroud)

据我所知,constructor任何内部方法都不使用该属性,只能由用户生成的代码使用.