This is probably a basic question, and I am aware that there have been some similar questions around here, but still I did not find an answer. Please consider the following code:
function Outer(inner2) {
var x = 5;
this.inner1 = function() {return (x);}
this.inner2 = inner2.bind(this);
}
var outer = new Outer(function() {return (x);});
alert(outer.inner1()); // works
alert(outer.inner2()); // does not work
If I would replace the second line by this.x = 5;, the second alert would work. So I guess the problem is that x when declared with var is not part of this, so that bind will have no effect.
Is there any way to make this work without using this.x?
x when declared with var is not part of this- correct.thisor lift it out somehow.this.x, you might want to pass it as an argument to your inner2 method :var outer = new Outer(function (x) { return (x); });andthis.inner2 = inner2.bind(this, x)outer.inner2(). So, the compiler could infer the context.x, and I do not want to pass each of them...