this
is confusing, so I condesed what I have learned from MDN and Yehuda's Blog into a cheatsheet
function hello(thing) {
console.log("Hello " + thing);
}
// this:
hello("world")
// desugars to:
hello.call(window, "world");
But for strict mode, it will not refer to the global object window
var person = {
name: "Brendan Eich",
hello: function(thing) {
console.log(this + " says hello " + thing);
}
}
// this:
person.hello("world")
// desugars to this:
person.hello.call(person, "world");
Notice that for member function, this
becomes the object person
, instead of the global object window
function hello(thing) {
console.log(this + " says hello " + thing);
}
person = { name: "Brendan Eich" }
person.hello = hello;
person.hello("world") // still desugars to person.hello.call(person, "world")
hello("world") // "[object DOMWindow]world"
Notice how this
is not persistent and can yield surprising results. Thus, bind
solves the problem by binding this
to a specific object.
Global object, window
Global object, window
, if not in strict mode
A regular object
To avoid confusion and let this
be presistent