0

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

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.