I always see code written like this:
function F() {};
var obj = {...}
F.prototype = obj;
F.prototype.constructor = F // why need this
After reseting the prototype: F.prototype = obj
, why is the last line required? What does this reset the constructor too and is it always needed?
All Javascript objects inherit properties from the prototype object of their constructor.
Then, how do they also inherit properties from the Object class?
Remember that the prototype object is itself an object, it is created with the Object()
constructor. This means that the prototype object itself inherits properties from Object.prototype
.
If we use the default prototype object that is created when we define the F( )
constructor, we get a subclass of Object.To get a subclass of obj
here, we must explicitly create our prototype object.
function F() {};
var obj = {...}
F.prototype = obj();
Since the prototype object was created with the obj()
constructor,it has a constructor property that refers to the constructor of obj
object.But we want F
objects to have a different constructor that is F()
.That's why we've got to reassign this default constructor property.
F.prototype.constructor = F;
i hope this has helped you.