0

当我检查instanceof方法时,结果不一样。

function A(){}
function B(){};

首先,我将prototype(参考)属性分配到A

A.prototype = B.prototype;
var carA =  new A();

console.log( B.prototype.constructor );
console.log( A.prototype.constructor == B );
console.log( B.prototype.constructor == B );
console.log( carA  instanceof A );
console.log( carA  instanceof B );

上面返回的最后 4 个条件true

但是当我试图分配constructorB .. 结果不一样。

A.prototype.constructor = B.prototype.constructor;
var carA =  new A();

console.log( B.prototype.constructor );
console.log( A.prototype.constructor == B );
console.log( B.prototype.constructor == B );
console.log( carA  instanceof A );
console.log( carA  instanceof B );

在这种情况下carA instanceof B返回false。为什么它返回 false

4

1 回答 1

1

我从链接中找到了答案.. https://stackoverflow.com/a/12874372/1722625

instanceof实际上检查[[Prototype]]左侧对象的内部。和下面一样

function _instanceof( obj , func ) {
    while(true) {
       obj = obj.__proto__; // [[prototype]] (hidden) property
       if( obj == null) return false;
       if( obj ==  func.prototype ) return true;
    }
}

// which always true 
console.log( _instanceof(carA , B ) == ( obj instanceof B ) ) 

如果它返回true,objinstanceofB

于 2013-07-17T14:30:55.183 回答