it's all about prototype chain buddy
self here refers to the created object constructor
No,here self refers to created instances of the constructor not the constructor itself.Otherwise it is the global window object.
Machine.apply(this);
this statement makes coffeeMachine inherit all the methods and properties form Machine constructor.So ,it creates a parent-child relationship betwween those two where Machine is the parent class and coffeeMachine is child class.
it creates a prototype chain between them.If you are looking for a property or method on child instances ,but it is not defined in the child constructor ,interpreter goes down below the prototype chain looking for it.If it finds inside parents constructor ,then that property/method's value is used
inside coffeMachine this refers to global object.When you create new instance of coffeeMachine then this refers to the newly created object. When you create a new instance of coffeeMachine var parentEnable = this.enable;
looks for this.enabled
in the prototype chain.
As this.enabled method is preceded by var parentEnable=this.enabled It doesn't find it in the coffeMachine constructor .So it looks deep inside the prototype chain
and finds it in parent.Thats how parent's this.enabled
is assigned to var parentEnable
.
if coffeeMachine's this.enabled is defined before the var parentEnabled
then coffeMachine's this.enabled function will be assigned to parnetEnabled
function CoffeeMachine() {
Machine.apply(this);
this.enable = function() {
parentEnable();
/// this.run();
}
var parentEnable = this.enable; // it is now function(){parentEnable();///this.run()};
}
var coffeeMachine = new CoffeeMachine();
coffeeMachine.enable();
These two links have good explanatin about prototype chain in javascript: