JavaScript this Keyword, call, apply and bind Explained
this is the most misunderstood keyword in JavaScript, because its value is not fixed where a function is written but decided by how the function is called. That is why a page-object method works when called as loginPage.open() and breaks when passed as a callback. In this lesson you will learn the simple rules that decide this, how arrow functions differ, and how call, apply and bind let you control it.
📖 What You’ll Learn: what this is, the four binding rules (method call, plain call, explicit binding, new), this in strict mode, this in arrow functions, this in classes, losing this in callbacks and how to fix it, call, apply and bind, borrowing methods, and a page-object style example.
🎯 What Is this?
Definition: this is a special value available inside a (non-arrow) function. It refers to the object the function is working on, and it is set each time the function is called, based on how it is called.
Four rules decide it, checked in this order:
| Call style | Example | this is |
|---|---|---|
With new | new User() | The newly created object |
| Explicit binding | fn.call(obj), fn.apply(obj), fn.bind(obj)() | obj |
| Method call | obj.fn() | The object before the dot: obj |
| Plain call | fn() | undefined in strict mode; the global object in sloppy mode |
Arrow functions ignore all four rules: they use the this of the surrounding code (lexical this).
📍 Rule 1: Method Calls
When a function is called as a property of an object, this is that object:
📄 method-call.js
const loginPage = {
url: "/login",
attempts: 0,
open() {
this.attempts++;
return `opening ${this.url} (attempt ${this.attempts})`;
},
};
console.log(loginPage.open());
console.log(loginPage.open());
const cartPage = { url: "/cart", attempts: 0, open: loginPage.open };
console.log(cartPage.open()); // same function, different object before the dot
⌨️ Terminal
node method-call.js
🖥️ Output
opening /login (attempt 1)
opening /login (attempt 2)
opening /cart (attempt 1)
The same function gives different results depending on which object it is called on. this belongs to the call, not to the function.
🕳️ Rule 2: Plain Calls and Strict Mode
If you take a method out of its object and call it on its own, there is no object before the dot. In strict mode (ES modules, classes, "use strict") this is then undefined, so reading a property throws:
📄 plain-call.js
"use strict";
const loginPage = {
url: "/login",
open() {
return `opening ${this.url}`;
},
};
const open = loginPage.open; // copy the function out of the object
console.log(typeof open);
console.log(open()); // plain call: this is undefined
⌨️ Terminal
node plain-call.js
🖥️ Output
function
/home/you/js-course/plain-call.js:6
return `opening ${this.url}`;
^
TypeError: Cannot read properties of undefined (reading 'url')
at open (/home/you/js-course/plain-call.js:6:28)
at Object.<anonymous> (/home/you/js-course/plain-call.js:12:13)
Node.js v26.13.0
In sloppy mode this would be the global object instead, so this.url would quietly be undefined. Strict mode turns the silent bug into a clear error, which is one more reason to prefer it.
🔁 Losing this in Callbacks
The same problem happens whenever you pass a method as a callback, because the receiving function calls it as a plain function:
📄 lost-this.js
"use strict";
const reporter = {
prefix: "[REPORT]",
log(message) {
return `${this.prefix} ${message}`;
},
};
try {
console.log(["login ok", "cart ok"].map(reporter.log));
} catch (e) {
console.log(e.constructor.name + ":", e.message);
}
// Fix 1: wrap in an arrow function so it is still a method call
console.log(["login ok", "cart ok"].map((m) => reporter.log(m)));
// Fix 2: bind this permanently
console.log(["login ok", "cart ok"].map(reporter.log.bind(reporter)));
⌨️ Terminal
node lost-this.js
🖥️ Output
TypeError: Cannot read properties of undefined (reading 'prefix')
[ '[REPORT] login ok', '[REPORT] cart ok' ]
[ '[REPORT] login ok', '[REPORT] cart ok' ]
💡 Tip: When you see “Cannot read properties of undefined” inside a method that works elsewhere, check how it was called. A method passed to map, setTimeout, addEventListener or a test hook has usually lost its this.
➡️ this in Arrow Functions
Arrow functions do not have their own this; they use the this of the code where they are written. Inside a method, that is exactly what you want for callbacks:
📄 arrow-this.js
const suite = {
name: "Checkout",
tests: ["add item", "pay"],
list() {
return this.tests.map((t) => `${this.name} › ${t}`); // arrow uses list's this
},
};
console.log(suite.list());
const broken = {
name: "Broken",
list: () => typeof this, // arrow at object level: not the object
};
console.log(broken.list());
⌨️ Terminal
node arrow-this.js
🖥️ Output
[ 'Checkout › add item', 'Checkout › pay' ]
object
Rule of thumb: use method shorthand for methods, and arrow functions for callbacks inside methods. The Arrow Functions lesson has more examples.
🏗️ Rule 3: this with new and in Classes
When a function is called with new (or a class is instantiated), JavaScript creates a new object and sets this to it. In class methods, this is the instance the method is called on:
📄 class-this.js
class Counter {
count = 0;
increment() {
this.count++;
return this.count;
}
}
const c = new Counter();
console.log(c.increment(), c.increment());
const inc = c.increment; // detached method
try {
inc();
} catch (e) {
console.log(e.constructor.name + ":", e.message);
}
⌨️ Terminal
node class-this.js
🖥️ Output
1 2
TypeError: Cannot read properties of undefined (reading 'count')
Class bodies are always strict, so a detached method gets this === undefined. A common fix in classes is an arrow-function field, which captures the instance:
📄 arrow-field.js
class Button {
label = "Save";
click = () => `clicked ${this.label}`; // arrow field: this is the instance
}
const handler = new Button().click;
console.log(handler());
⌨️ Terminal
node arrow-field.js
🖥️ Output
clicked Save
Classes are covered fully in Module 8.
📞 call and apply: Choose this for One Call
Definition: fn.call(thisArg, arg1, arg2, ...) calls fn once with this set to thisArg. fn.apply(thisArg, [arg1, arg2]) does the same but takes the arguments as an array.
📄 call-apply.js
function describe(env, browser) {
return `${this.name} on ${env} using ${browser}`;
}
const smoke = { name: "Smoke suite" };
const regression = { name: "Regression suite" };
console.log(describe.call(smoke, "qa", "chromium"));
console.log(describe.apply(regression, ["staging", "firefox"]));
⌨️ Terminal
node call-apply.js
🖥️ Output
Smoke suite on qa using chromium
Regression suite on staging using firefox
💡 Tip: Memory aid: Apply takes an Array, Call takes Commas. With spread syntax, fn.call(obj, ...args) can replace apply in modern code.
Borrowing methods
call lets you use a method from one object on another object, for example array methods on array-like objects:
📄 borrow.js
function joinArgs() {
// arguments is array-like, not a real array, so it has no join method
return Array.prototype.join.call(arguments, " | ");
}
console.log(joinArgs("login", "search", "cart"));
const arrayLike = { 0: "a", 1: "b", length: 2 };
console.log(Array.prototype.map.call(arrayLike, (x) => x.toUpperCase()));
console.log(Array.from(arrayLike)); // modern alternative: convert first
⌨️ Terminal
node borrow.js
🖥️ Output
login | search | cart
[ 'A', 'B' ]
[ 'a', 'b' ]
🔗 bind: Fix this Permanently
Definition: fn.bind(thisArg, ...presetArgs) does not call fn. It returns a new function whose this is permanently set to thisArg, optionally with some arguments filled in already (partial application).
📄 bind.js
const api = {
baseURL: "https://qa.example.com",
get(path) {
return `GET ${this.baseURL}${path}`;
},
};
const get = api.get.bind(api); // safe to pass around
console.log(get("/users"));
console.log(["/orders", "/cart"].map(get)); // still works as a callback
function multiply(a, b) {
return a * b;
}
const double = multiply.bind(null, 2); // preset the first argument
console.log(double(21));
const bound = api.get.bind(api);
console.log(bound.call({ baseURL: "https://evil.example" }, "/x")); // bind wins over call
⌨️ Terminal
node bind.js
🖥️ Output
GET https://qa.example.com/users
[
'GET https://qa.example.com/orders',
'GET https://qa.example.com/cart'
]
42
GET https://qa.example.com/x
| Method | Calls the function now? | Arguments | Returns |
|---|---|---|---|
call | Yes | One by one | The function’s result |
apply | Yes | As an array | The function’s result |
bind | No | Optional preset arguments | A new bound function |
🧪 Tester Scenario: A Page Object Used Safely in Callbacks
Page objects are classes or objects whose methods use this to reach their URL, locators and helpers. This simulated page object shows a failing callback and the two standard fixes:
📄 page-object.js
class SearchPage {
constructor(baseURL) {
this.baseURL = baseURL;
this.history = [];
}
search(term) {
const url = `${this.baseURL}/search?q=${encodeURIComponent(term)}`;
this.history.push(url);
return url;
}
}
const page = new SearchPage("https://qa.example.com");
const terms = ["laptop", "usb cable"];
try {
terms.forEach(page.search); // this is undefined inside search
} catch (e) {
console.log("broken:", e.message);
}
terms.forEach((t) => page.search(t)); // fix 1: arrow wrapper
terms.forEach(page.search.bind(page)); // fix 2: bind
console.log(page.history);
⌨️ Terminal
node page-object.js
🖥️ Output
broken: Cannot read properties of undefined (reading 'baseURL')
[
'https://qa.example.com/search?q=laptop',
'https://qa.example.com/search?q=usb%20cable',
'https://qa.example.com/search?q=laptop',
'https://qa.example.com/search?q=usb%20cable'
]
In Playwright, page objects are usually called directly inside an async test (await loginPage.login(user)), which is a method call and keeps this. The problem appears when methods are passed to helpers, array methods or event handlers.
📝 Practice Questions with Answers
Try each question on your own first, then open the answer to check your work. Run the code with node practice.js.
Q1. Create an object user with name and a method greet() that returns "Hi, I am <name>" using this.
Show answer
📄 practice1.js
const user = {
name: "Asha",
greet() {
return `Hi, I am ${this.name}`;
},
};
console.log(user.greet());🖥️ Output
Hi, I am AshaQ2. Use call to run function intro(role) { return `${this.name} is a ${role}`; } for { name: "Ravi" } with the role "tester", then use apply for { name: "Meera" } with "developer".
Show answer
📄 practice2.js
function intro(role) {
return `${this.name} is a ${role}`;
}
console.log(intro.call({ name: "Ravi" }, "tester"));
console.log(intro.apply({ name: "Meera" }, ["developer"]));🖥️ Output
Ravi is a tester
Meera is a developerQ3. This prints undefined items. Fix it in two different ways.
const cart = {
items: 3,
report() { return `${this.items} items`; },
};
const show = cart.report;
console.log(show());Show answer
📄 practice3.js
const cart = {
items: 3,
report() { return `${this.items} items`; },
};
const show1 = () => cart.report(); // fix 1: call it as a method
const show2 = cart.report.bind(cart); // fix 2: bind
console.log(show1(), "|", show2());🖥️ Output
3 items | 3 itemsQ4. Use bind to create addTax from function withRate(rate, amount) { return amount * (1 + rate); } with the rate fixed at 0.18, and print addTax(1000).
Show answer
📄 practice4.js
function withRate(rate, amount) {
return amount * (1 + rate);
}
const addTax = withRate.bind(null, 0.18);
console.log(addTax(1000));🖥️ Output
1180null is passed as this because the function does not use this.
Q5. Predict the output, then run it.
const obj = {
name: "obj",
regular() { return this.name; },
arrow: () => typeof this,
nested() { return (() => this.name)(); },
};
console.log(obj.regular(), obj.arrow(), obj.nested());Show answer
📄 practice5.js
const obj = {
name: "obj",
regular() { return this.name; },
arrow: () => typeof this,
nested() { return (() => this.name)(); },
};
console.log(obj.regular(), obj.arrow(), obj.nested());🖥️ Output
obj object objregular is a method call. arrow takes this from the module scope (an empty module.exports object in CommonJS), not from obj. The arrow inside nested uses nested‘s this, which is obj.
Q6. Use Array.prototype.filter.call to get the even numbers from the array-like object { 0: 4, 1: 7, 2: 10, length: 3 }.
Show answer
📄 practice6.js
const arrayLike = { 0: 4, 1: 7, 2: 10, length: 3 };
console.log(Array.prototype.filter.call(arrayLike, (n) => n % 2 === 0));🖥️ Output
[ 4, 10 ]🧠 MCQ Quiz: this, call, apply and bind
10 questions on this lesson. Pick one answer for each, then press Check answers to see your score and an explanation for every question.
- What decides the value of this in a regular function?Answer: How the function is called. Arrow functions are the exception: they use lexical this.
- In
user.save(), what is this inside save?Answer: user. The object before the dot. - In strict mode, what is this in a plain call
fn()?Answer: undefined. Sloppy mode would use the global object instead. - Why does
[1, 2].map(obj.method)often fail?Answer: The method is called without its object, so this is lost. Use (x) => obj.method(x) or obj.method.bind(obj). - What is the difference between call and apply?Answer: apply takes arguments as an array. call takes arguments separately.
- What does bind return?Answer: A new function with this fixed. bind does not call the function.
- Can call change the this of a function created with bind?Answer: No, the bound this wins. A bound function ignores a new thisArg (except when called with new).
- Where does an arrow function get this?Answer: From the surrounding code where it is defined. call, apply and bind cannot change an arrow function’s this.
- What is this inside a constructor called with new?Answer: The newly created object. new creates an object and binds this to it.
- Which is a good way to keep this in a class method used as an event handler?Answer: An arrow-function class field or bind in the constructor. Both capture the instance permanently.
💼 Interview Questions and Answers
Q1. Explain how this is determined in JavaScript.
For regular functions it depends on the call: with new it is the new object; with call/apply/bind it is the given object; called as obj.method() it is obj; called as a plain function it is undefined in strict mode (global object in sloppy mode). Arrow functions have no own this and use the this of the enclosing scope. Class bodies and ES modules are strict.
Q2. What is the difference between call, apply and bind?
call(thisArg, a, b) and apply(thisArg, [a, b]) invoke the function immediately with a chosen this; they differ only in how arguments are passed. bind(thisArg, ...preset) returns a new function with this (and optionally leading arguments) permanently fixed, to be called later, typically as a callback.
Q3. Predict the output.
📄 predict.js
"use strict";
const counter = {
value: 10,
get() { return this?.value; },
};
const { get } = counter;
console.log(counter.get(), get(), get.call({ value: 99 }), get.bind(counter)());
⌨️ Terminal
node predict.js
🖥️ Output
10 undefined 99 10
counter.get() is a method call (10). Destructuring copies the function out, so get() is a plain strict-mode call where this is undefined (the ?. avoids a crash and gives undefined). call supplies { value: 99 }, and bind(counter) restores 10.
Q4. How do you fix “Cannot read properties of undefined” inside a class method used as a callback?
The method was called without its instance. Options: wrap the call in an arrow function (items.forEach((i) => this.process(i))), bind it (this.process = this.process.bind(this) in the constructor), or define it as an arrow-function class field (process = (i) => {...}). Choose one convention per project.
❓ Frequently Asked Questions
🤔 What is this in the global scope?
In a browser classic script it is window. In an ES module it is undefined. In a Node.js CommonJS file it is module.exports (an empty object by default).
🤔 Can I change this in an arrow function with call or bind?
No. Arrow functions ignore the thisArg of call, apply and bind, because they have no this of their own.
🤔 Is bind still needed with arrow functions available?
Less often. Arrow functions solve most callback cases, but bind is still useful for partial application and for passing existing methods as callbacks.
🤔 Why does this behave differently in strict mode?
Strict mode stops plain function calls from defaulting this to the global object, so mistakes throw errors instead of silently reading or writing global properties.
🏁 Summary
thisis set by how a regular function is called:new, explicit binding, method call, or plain call.- In strict code (modules, classes) a plain call has
this === undefined; passing a method as a callback loses itsthis. - Arrow functions use lexical
this: great for callbacks inside methods, wrong for object methods. callandapplyinvoke a function with a chosenthis;bindreturns a new function withthisfixed.- Fix lost
thiswith an arrow wrapper,bind, or an arrow-function class field.
Next, continue with Lesson 24: Recursion.
🎬 Watch JavaScript and automation tutorials on YouTube!
Subscribe to SqaToolsByDY • Practice on sqatools.in