Quick revision notes with examples and common interview pitfalls.
function show() {
console.log(this);
}
show();For a regular function call, this depends on how the function is invoked.
In strict mode:
"use strict";
show(); // undefinedWithout strict mode in the browser, it is usually:
windowIf the function is called like this:
show()then this is global object or undefined, not the nearest function scope.
const user = {
name: "Zoltan",
show() {
console.log(this.name);
}
};
user.show();ZoltanHere the function is called as:
user.show()So:
this === userthis = the object on the left side of the dot at call time
const user2 = {
name: "Zoltan",
show() {
console.log(this.name);
}
};
const fn = user2.show;
fn();undefinedThis is no longer called as:
user2.show()Now it is:
fn()So it becomes a normal function call.
This is one of the most common interview questions.
const user3 = {
name: "Zoltan",
show: () => {
console.log(this);
}
};
user3.show();Arrow functions do not have their own this.
They inherit this from the outer lexical scope.
That means:
this !== user3This is why arrow functions are usually not recommended as object methods.
Calls the function immediately and sets this manually.
function show(age, role) {
console.log(this.name, age, role);
}
const user = {
name: "Zoltan"
};
show.call(user, 50, "Frontend Engineer");Zoltan 50 Frontend Engineerfn.call(thisArg, arg1, arg2)call() lets you explicitly define what this should be.
Same as call(), but arguments are passed as an array.
function show(age, role) {
console.log(this.name, age, role);
}
const user = {
name: "Zoltan"
};
show.apply(user, [50, "Frontend Engineer"]);Zoltan 50 Frontend Engineerfn.apply(thisArg, [args])The only difference is argument format.
show.call(user, 50, "FE")show.apply(user, [50, "FE"])Returns a new function with permanently fixed this.
function show() {
console.log(this.name);
}
const user = {
name: "Zoltan"
};
const boundFn = show.bind(user);
boundFn();ZoltanUnlike call() and apply(), bind() does not execute immediately.
It returns a new function.
const newFn = fn.bind(thisArg)const user = {
name: "Zoltan",
show() {
console.log(this.name);
}
};
const fn = user.show.bind(user);
fn();ZoltanCommon interview example.
const user = {
name: "Zoltan",
show() {
console.log(this.name);
}
};
setTimeout(user.show.bind(user), 1000);Without bind(), this would be lost inside the callback.
obj.fn()→this = objfn()→this = undefined / window() => {}→ outerthis
call now
Runs immediately.
apply array
Arguments come as array.
bind later
Returns new function.