I've Googled this like crazy, and I still don't understand.
If I set up child and parent objects like the following:
var Child = function(name, toy)
{
this.toy = toy;
Parent.call(this, name);
}
var Parent = function(name)
{
this.name = name;
}
//Child.prototype = new Parent();
I do not need to uncomment the above line so as to be able to get the following result:
var bobby = new Child("Robert", "Lego");
document.write(bobby.name + " " + bobby.toy);
//Result: Robert Lego
My (probably incorrect) understanding is that the line
Child.prototype = new Parent();
sets the prototype of what is created by the Child constructor to be what is created by the Parent constructor. Hence, without this line, the line
Parent.call(this, name);
(which I believe calls the Parent constructor, setting the this context to Child, and passes in name) shouldn't actually work.
What is wrong with my understanding?
Thanks in advance for any help! :)
Javascript doesn't know that a function is a constructor. It's only treated as one when you call it using the
newkeyword. If you were to call it withoutnew, it would behave differently.Parent.call(this, name)simply callsParentas a regular function, using the newly constructedChild(because you used thenewkeyword when you constructed a Child) as itsthis.So all your function
parentdoes in this case is assign the name to the object that it received. In this case, theChildthat you just constructed.Compare your Child to this:
Here, the child function is using
Parentas a constructor.