Get a handle on what this refers to in JavaScript, blow away the fog surrounding this, understand who determines what this refers to, and by the end of this article you’ll be able to determine what this refers to before your code even runs.
We’ve all seen this in different ways in functions, but still can’t figure out exactly who this refers to in JavaScript. This article will give you a complete grasp of this.
var addTo = function(passed){ var inner = 2; return passed + inner; } console.log(addTo(3)); / / 5Copy the code
The five rules
(1) If the new keyword appears before the function being called, the JavaScript engine creates a new object, and this in the function being called refers to the newly created object.
function ConstructorExample() {
console.log(this);
this.value = 10;
console.log(this);
}
new ConstructorExample();
// -> ConstructorExample {}
// -> ConstructorExample { value: 10 }
Copy the code
(2) If a function is triggered by apply, call, or bind, this points to the first argument passed to the function.
function fn() {
console.log(this);
}
var obj = {
value: 5
};
var boundFn = fn.bind(obj);
boundFn(); // -> { value: 5 }
fn.call(obj); // -> { value: 5 }
fn.apply(obj); // -> { value: 5 }
Copy the code
(3) If a function is a method of an object, and the object fires the function with a period symbol, then this refers to the object on which the function is an attribute of that object, that is, this refers to the object to the left of the period.
var obj = { value: 5, printThis: function() { console.log(this); }}; obj.printThis(); // -> {value: 5, printThis: ƒ}Copy the code
(4) If a function is called as FFI, it means that the function does not comply with any of the above calls. This refers to the global object, which in the browser is window.
function fn() {
console.log(this);
}
// If called in browser:
fn(); // -> Window {stop: ƒ, open: ƒ, alert: ƒ, ...}
Copy the code
Note that rule 4 is similar to rule 3, except that when a function is not called as a method, it implicitly becomes the property of the global object — window. So when we call fn(), which is window.fn(), according to the third rule, this in fn() refers to window.
function fn() {
console.log(this);
}
// In browser:
console.log(fn === window.fn); // -> true
Copy the code
(5) If the accumulation of the above rules occurs, the priority decreases from 1 to 4, and the direction of this is judged according to the rule with the highest priority.