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?

Kramer Li
  • 2,284
  • 5
  • 27
  • 55
  • According to [this](https://stackoverflow.com/a/6529410/5156549) - **You can't change the constructors of an object, you can however change the 'type' of the object the constructor returns.** – 0_0 Feb 15 '18 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. – georg Feb 15 '18 at 16:34

1 Answers1

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.

trincot
  • 317,000
  • 35
  • 244
  • 286