I am a beginner in js, and am puzzled by the following code:
Foo = function(arg) {
this.arg = arg;
};
Foo.prototype = {
init: function () {
var f = function () {
alert("current arg: " + this.arg); // am expecting "bar", got undefined
}
f();
}
};
var yo = Foo("bar");
yo.init();
I was expected to get "current arg: bar", but got "current arg: undefined". I noticed that by copying this.arg into a "normal" variable first, and refering this variable in the closure works:
Foo.prototype = {
init: function () {
var yo = this.arg;
var f = function () {
alert("current arg: " + yo); }
f();
}
};
Am I doing something wrong, got wrong expectations, or does it fall into one of the js WTF ?
Vanilla functions will be run with
this
referring towindow
. Your second piece of code is a perfect example of how to work around this problem using closures.(You can also use
call
andapply
to call a function with a particular context.)It depends on how the function was invoked.
If invoked with keyword
new
thenthis
refers to the object being constructed (which will be implicitly returned at the end of the function).If invoked as a normal function,
this
refers to the globalwindow
object.Example:
JavaScript doesn't have "constructors" per se, the only way JavaScript knows that your
function
is actually a "constructor" is invokation style (namely you using keywordnew
whenever you invoke it)