Was reading through MDN and came across this
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
Why is it that this
inside the function growUp()
binds to window
?
Because this
is not bound to anything else. If it is not bound then it is bound when called to default object. Default is global window
object.
If you need to bind it to person you can explicitly do it with bind
function:
function Person() {
this.age = 0;
setInterval(function growUp() {
this.age++;
}.bind(this), 1000);
}
var p = new Person();
Edit:
In javascript you have two ways of calling function:
As function itself
function f() {}
f();
As property of the object
var obj = {
f: function() {}
};
obj.f();
Via object prototype:
function X() {}
X.protoype.f = function() {}
var x = new X();
x.f()
For the first case this
is not defined and need to be set to something. By default it is global object (window
object in browser).
For the second and third case this
is set to the object before dot '.' and they differs only how the function is found.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments