0

It is said that in java script the interpretor use the constructor attribute to determain type of object.

For example:

function Person(name){this.name=name}

var person = new Person('jack')

In this case the person.constructor will be function Person

So I think if I change the person.constructor = some other constructor function

The java script interpretor will recognize person as another type.

Here is my test

function Car(brand){this.brand=brand}

person.constructor = Car

person.__proto__.constructor = Car

person instanceof Car 
return false

Why interpretor still recognize person as type of Person nor Car?

2
  • According to this - You can't change the constructors of an object, you can however change the 'type' of the object the constructor returns. Commented Feb 15, 2018 at 16:28
  • X instanceof Y is the same as X.__proto__ == Y.prototype. constructor is only informational, changing it doesn't have any effect. Commented Feb 15, 2018 at 16:34

1 Answer 1

0

First, don't use the __proto__ property of objects: although standardised in EcmaScript2015, it is also deprecated in favour of Object.setPrototypeOf. Both work however if you change the prototype, not the constructor:

function Person(name){this.name=name}

var person = new Person('jack')

function Car(brand){this.brand=brand}

Object.setPrototypeOf(person, Car.prototype);
// This also works:
// person.__proto__ = Car.prototype;

console.log(person instanceof Car); // true

So it is not the constructor property that defines the prototype chain, but the __proto__ property.

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

1 Comment

Could you please let me know whether this answered your question?

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.