Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it necessary to set the 'prototype.constructor' property of a class in Javascript? [duplicate]

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?

like image 298
Eugene Yarmash Avatar asked Nov 04 '22 07:11

Eugene Yarmash


1 Answers

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.

like image 67
Eugeny89 Avatar answered Nov 11 '22 07:11

Eugeny89