0

I working out the inheritance and OOPS in JavaScript. I created 'A' object and 'B' object and inherited all the properties of 'B' to 'A'.

While I check the newly created object instance by using 'instanceof', I am getting both objects are true.
But I have created the object using 'B' constructor only.

function A(){
    this.a = "test1",
    this.b = "test2"
}

function B(){
    this.c = "test3",
    this.d = "test4"
}

B.prototype = new A();

var userObj = new B();

console.log(userObj instanceof B); // true
console.log(userObj instanceof A); // true, How this can be true?

3 Answers 3

4

In JavaScript, the inheritance is prototype-based. That means that there are no classes. Instead, an object inherits from another object.

What you have done here is, object B inherits from object A because of this:

B.prototype = new A();

So ,now, userObj (instance of object B) of-course becomes instance of object A, (thats what inheritance is all about, right?)

So thats the reason

console.log(userObj instanceof B); // true
console.log(userObj instanceof A); //  Also true?
Sign up to request clarification or add additional context in comments.

Comments

1

Prototype object has a built in property called constructor.First see this image from chorme console than i will discuss

enter image description here

In your code B.prototype = new A(); =>this statement sets B's prototype to a instance of A.So B's prototype object has it's constructor property assigned to A();

console.log(userObj.constructor // it will show A.But it is not true

Remember it is not userObj's constructor.The constructor you get is from prototype obj.

console.log(userObj instanceof A); // true, How this can be true?

As userObj is a instance of B.And B inherits from A.So userObj is also a instance of A.But you can manipulate the constructor property set to B using

B.prototype.constructor=B;

Comments

0

console.log(userObj instanceof A); you will surely get true. This is as per the JavaScript standard.

When you are creating a object of B which inherits all the properties of A , the object contains a link __proto__ which points to A's Prototype.

So instanceof will find the A's constructor in the prototypical chaining of the Object B.

That's why it returns true.

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.