5

Possible Duplicate:
What it the significance of the Javascript constructor property?

In the Javascript docs at developer.mozilla.org, on the topic of inheritance there's an example

// inherit Person
Student.prototype = new Person();

// correct the constructor pointer because it points to Person
Student.prototype.constructor = Student;

I wonder why should I update the prototype's constructor property here?

Community
  • 1
  • 1
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378

1 Answers1

2

Each function has a prototype property (even if you did not define it), prototype object has the only property constructor (pointing to a function itself). Hence after you did Student.prototype = new Person(); constructor property of prototype is pointing on Person function, so you need to reset it.

You should not consider prototype.constructor as something magical, it's just a pointer to a function. Even if you skip line Student.prototype.constructor = Student; line new Student(); will work as it should.

constructor property is useful e.g. in following situations (when you need to clone object but do not know exactly what function had created it):

var st = new Student();
...
var st2 = st.constructor();

so it's better to make sure prototype.constructor() is correct.

Eugeny89
  • 3,797
  • 7
  • 51
  • 98
  • The `var st2 = st.constructor();` misses the `new` keyword. It should be `var st2 = new st.constructor();` – golem Jan 21 '16 at 17:16