what is the this (inside inner functions) referring to in the following code context? Does it point to TimeSpan?
var TimeSpan = function (da
The this
value is set implicitly depending on how the function is invoked, there are three cases where this happens:
When a reference with no base-object, or a non-reference is invoked:
myFn(); // the myFn reference has no base object
(function () {})(); // non-reference
The this
value will point to the global object 1
When a reference contains a base object, for example:
myObj.method();
The this
value inside method
will point to myObj
.
When the new
operator is used:
var obj = new Foo();
The this
value inside the Foo
function, will point to a newly created object that inherits from Foo.prototype
.
The this
value can be set also explicitly, by using the call and apply methods, for example, with call
:
function test(a) {
return alert(this + a);
}
test.call("hello", " world"); // alerts "hello world"
Or with apply
if we need to "apply" a set of arguments from an array to a function:
function test(a, b) {
return alert(this + a + b);
}
var args = ["my ", "world "];
test.apply("hello ", args); // alerts "hello my world"
[1] This has changed on the new ECMAScript 5th Strict Mode, now when a function reference with no base object, or a non-reference is invoked (as the first case), the this
value will contain undefined
.
This was made because when working with constructor functions, people often forgot to use the new
operator when calling the constructor.
When that happened, the this
value pointed to the global object, and that ended up adding unwanted global properties.
Now on strict mode, this
will contain undefined, and if property lookup is made on it (this.foo = 'foo'
) we will have a nice TypeError
exception, instead of having a global foo
property.