If a variable is not available in a function when it's needed, then it's being looked for in the scope chain (which is a closure), but other times it's being searched for in the prototype chain. I am trying to wrap my head around which is happening when. I was wondering if someone could kindly clear the mist for me, or refer me to some literature discussing this topic specifically.
For example, would I be right saying that: - Objects and therefore public variables tied to the context (this)are always looked up in the prototype chain? - Private variables are always looked up in the scope chain (i.e. chain of functions in the execution context)? - Are there any cases when the program is looking in both/either?
I tested three different scenarios(scope chain look-up, prototype look-up and no look-up), but unfortunately It haven't helped enough to get to the bottom of this.
var Food = function(){
var t = 1; // for closure
this.timeToPrepare = function(){ // Scope chain lookup
console.log(t * 3);
};
this.timeToMake = function(){ // This is looked up in the prototype chain
console.log(this.t * 3);
};
this.timeToEat = function(t){ //No lookup
console.log(t * 3);
};
};
Food.prototype.t = 2;
(function(){
var pizza = new Food;
pizza.timeToPrepare(); //3
pizza.timeToMake(); //6
pizza.timeToEat(3); //9
})();
Thanks!