this
this is defined/determined by how a function is called.this refers to the global object (window in browser, global in node.js)strict mode, this refers to the global objectstrict mode, this is undefinedfunction f2() {
"use strict"; // see strict mode
return this;
}
f2() === undefined; // truef2 is called directly. not as a method or a property of the window objectcall(), or apply()apply / callvar obj = { a: "Custom" };
var a = "Global";
function whatsThis() {
return this.a;
}
whatsThis(); // 'Global'
whatsThis.call(obj); // 'Custom'
whatsThis.apply(obj); // 'Custom'if you call a function without call or apply, this refers to the window object. However, if you call the same function with call or apply, you set this as the object with which you are calling the function.
if the value you are passing with call or apply is not an object, the browser will use the internal method ToObject() in order to convert it to an object.
bind
foo.bind(someObject) this is the someObject regardless of how the function is being called.bind more than once.function f() {
return this.a;
}
var g = f.bind({ a: "azerty" });
console.log(g()); // azerty
var h = g.bind({ a: "yoo" }); // bind only works once!
console.log(h()); // azertyarrow function