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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With