Chaining Javascript Constructors

1.1k views Asked by At

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! :)

1

There are 1 answers

2
ColBeseder On

Javascript doesn't know that a function is a constructor. It's only treated as one when you call it using the new keyword. If you were to call it without new, it would behave differently.

Parent.call(this, name) simply calls Parent as a regular function, using the newly constructed Child (because you used the new keyword when you constructed a Child) as its this.

So all your function parent does in this case is assign the name to the object that it received. In this case, the Child that you just constructed.

Compare your Child to this:

var Child = function(name, toy)
{
    var child = new Parent(name);
    child.toy = toy;
    return child;
}

Here, the child function is using Parent as a constructor.