Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript inheritance & Apply

Tags:

javascript

I have been looking into design patterns in Javascript and found http://tcorral.github.com/Design-Patterns-in-Javascript/Template/withoutHook/index.html to be a great source.

Can anyonne explain the significance of using ParentClass.apply(this)

var CaffeineBeverage = function(){

};
var Coffee = function(){
    CaffeineBeverage.apply(this);
};
Coffee.prototype = new CaffeineBeverage();

PS: I tried commenting the CaffeineBeverage.apply(this), but no effect was there. Here is a link to jsfiddle http://jsfiddle.net/pramodpv/8XqW9/

like image 328
Pramod Pallath Vasudevan Avatar asked Mar 01 '12 13:03

Pramod Pallath Vasudevan


2 Answers

It simply applies the parent constructor to the object being constructed. Try adding some stuff to the CaffeineBeverage constructor and you'll see what I mean.

var CaffeineBeverage = function(){
    this.tweakage = '123';
};

var Coffee = function(){
    CaffeineBeverage.apply(this);
};

Don't do this: Coffee.prototype = new CaffeineBeverage(). Do this instead:

Coffee.prototype = Object.create(CaffeineBeverage.prototype);

For more information on that, see this article, which also provides a shim for older browsers, which don't have Object.create.

Testing it out:

var drink = new Coffee();
console.log(drink.tweakage); // 123
like image 159
Dagg Nabbit Avatar answered Oct 03 '22 18:10

Dagg Nabbit


Instead of looking at that example, let's flesh out our own:

var Room = function()
{
  this.doors = 1;
};

Much like call, apply will execute the function, but allow you to specify what this is. In the example above, I'm specifying this.doors = 1, which makes doors a member when we've created our instance of Room.

Now, if I do this:

var ComputerRoom = function() 
{
  Room.apply(this);
  // I can now access the this.doors member:

  this.doors = this.doors + 1;
};

I'm actually saying that this in the context of the Room constructor, is actually the instance of ComputerRoom, which is why I pass it into the apply command: Room.apply(this).

like image 36
Matthew Abbott Avatar answered Oct 03 '22 18:10

Matthew Abbott