- The keyword "this" refers to whatever is left of the dot at call-time.
- If there's nothing to the left of the dot, then "this" is the root scope (e.g. Window).
- A few functions change the behavior of "this"—bind, call and apply
- The keyword "new" binds this to the object just created
So if you're using the value of "this" in someFunction...
thing.someFunction(); // this === thing
someFunction(); // this === Window
new someFunction(); // this === the newly created object
There are three ways to invoke a function. The meaning of this
depends on which method was used:
- If a function is invoked in the form
foo.func()
, then the value ofthis
isfoo
. - If a function is invoked in the form
func()
(sometimes called "bare"), then the value ofthis
is the "root object". In browsers the root object iswindow
, in Node this it's theglobal
object [0]. It's easier to make a bare invocation than you think:
var bareFunc = foo.func;
bareFunc();
- If a function is invoked via the
call()
orapply()
function, then the value ofthis
is whatever the invocation specifies. For example, infunc.call(foo)
the value ofthis
will befoo
.
If you ever pass a function to something else as a callback, you have no guarantee what the value of this
will be when it is called. For example, if you register a callback for a click event, the value of this
is whatever the caller wants it to be (in this case, it'll be the DOM element that's emitting the event):
function MyFoo(elem) {
elem.addEventListener('click', this.onClick);
}
MyFoo.prototype.onClick = function(e) {
// `this` is whatever the caller wanted it to be
}
You can force this
to be a specific value by using the bind()
function:
function MyFoo(elem) {
elem.addEventListener('click', this.onClick.bind(this));
}
MyFoo.prototype.onClick = function(e) {
// `this` has been bound to what you think it should be.
}
[0] However, if you're in strict mode, then in either case this
will be undefined
.