Reputation: 4144
When I checked instanceof
method, the results are not same .
function A(){}
function B(){};
First I assigned prototype
( reference ) property , into 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 );
The last 4 condition on above returns true
.
But when I tried to assign constructor
of B .. results are not same .
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 );
On this case carA instanceof B
returns false
. Why it returns false
Upvotes: 0
Views: 253
Reputation: 4144
I found answer from link .. https://stackoverflow.com/a/12874372/1722625
instanceof
actually checking internal [[Prototype]]
of left-hand object . Same like below
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 ) )
if it returns true, obj
is instanceof
B
Upvotes: 1