Functions nested under a prototype function do not get the this.variables defined for the prototype.
var Person, p;
Person = function(name, age) {
this.name = name;
this.age = age;
};
Person.prototype.getInfo = function() {
var innerFun;
innerFun = function() {
return this.name;
};
return "name: " + (innerFun()) + " age: " + this.age;
};
p = new Person('dork', 99);
console.log(p.getInfo()); // name: age: 99
I thought that since every function is an object, this would be different within every function definition; but the following code blows away that logic.
var getInfo;
getInfo = function() {
var display;
this.name = 'dork';
return display = function() {
return this.name;
};
};
console.log(getInfo()()); // dork
Is there a logic behind this behaviour or should I just take it as a rule and use call() to get around this problem?
Short version of
thisbehavior:x.f(),thiswill bex.(Note: invoked as
x.f(). It does not matter how and where you define it)f(),thiswill bewindow.x['f'](),thiswill bewindowx(not sure why I thought otherwise)f.call(x)orf.apply(x),thiswill bex.Again, the prototype does not matter, if you do
you will see that only calling style matters.