惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
P
Proofpoint News Feed
The Last Watchdog
The Last Watchdog
S
Secure Thoughts
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
N
News | PayPal Newsroom
Application and Cybersecurity Blog
Application and Cybersecurity Blog
O
OpenAI News
S
Security @ Cisco Blogs
宝玉的分享
宝玉的分享
Hacker News: Ask HN
Hacker News: Ask HN
T
Troy Hunt's Blog
Google Online Security Blog
Google Online Security Blog
WordPress大学
WordPress大学
有赞技术团队
有赞技术团队
TaoSecurity Blog
TaoSecurity Blog
Help Net Security
Help Net Security
Latest news
Latest news
NISL@THU
NISL@THU
S
Security Affairs
博客园_首页
C
CXSECURITY Database RSS Feed - CXSecurity.com
博客园 - 聂微东
AI
AI
www.infosecurity-magazine.com
www.infosecurity-magazine.com
Recent Announcements
Recent Announcements
P
Privacy & Cybersecurity Law Blog
小众软件
小众软件
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Hugging Face - Blog
Hugging Face - Blog
博客园 - 司徒正美
AWS News Blog
AWS News Blog
W
WeLiveSecurity
Google DeepMind News
Google DeepMind News
I
InfoQ
Schneier on Security
Schneier on Security
Recent Commits to openclaw:main
Recent Commits to openclaw:main
T
The Exploit Database - CXSecurity.com
IT之家
IT之家
T
Threatpost
Scott Helme
Scott Helme
L
LINUX DO - 热门话题
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
N
News and Events Feed by Topic
L
LINUX DO - 最新话题
F
Full Disclosure
大猫的无限游戏
大猫的无限游戏
H
Heimdal Security Blog
S
SegmentFault 最新的问题

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React Don't Confuse Function Expressions and Function Declarations in JavaScript How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them?
Dmitri Pavlutin · 2021-02-23 · via Dmitri Pavlutin Blog

In JavaScript this is the function invocation context.

The challenge is that this has a complicated behavior. That's why during a JavaScript coding interview you might be asked how this behaves in certain situations.

Since the best way to prepare for a coding interview is to practice, in this post I compiled a list of 7 interesting interview questions on this keyword.

If you're not familiar with this keyword, I recommend reading the post Gentle Explanation of "this" in JavaScript.

Note: JavaScript snippets below run in non-strict mode, also known as sloppy mode.

Table of Contents

  • Question 1: Variable vs property
  • Question 2: Cat name
  • Question 3: Delayed greeting
  • Question 4: Artificial method
  • Question 5: Greeting and farewell
  • Question 6: Tricky length
  • Question 7: Calling arguments
  • Summary

Question 1: Variable vs property

What logs to console the following code snippet:


const object = {

message: 'Hello, World!',

getMessage() {

const message = 'Hello, Earth!';

return this.message;

}

};

console.log(object.getMessage()); // What is logged?


Expand answer

'Hello, World!' is logged to console. Open the demo.

object.getMessage() is a method invocation, that's why this inside the method equals object.

There's also a variable declaration const message = 'Hello, Earth!' inside the method. The variable doesn't influence anyhow the value of this.message.

Question 2: Cat name

What logs to console the following code snippet:


function Pet(name) {

this.name = name;

this.getName = () => this.name;

}

const cat = new Pet('Fluffy');

console.log(cat.getName()); // What is logged?

const { getName } = cat;

console.log(getName()); // What is logged?


Expand answer

'Fluffy' and 'Fluffy' are logged to console. Open the demo.

When a function is invoked as a constructor new Pet('Fluffy'), this inside the constructor function equals the constructed object.

this.name = name expression inside Pet constructor creates name property on the constructed object.

this.getName = () => this.name creates a method getName on the constructed object. And since the arrow function is used, this inside the arrow function equals to this of the outer scope — the constructor function Pet.

Invoking cat.getName(), as well as getName(), returns the expression this.name that evaluates to 'Fluffy'.

Question 3: Delayed greeting

What logs to console the following code snippet:


const object = {

message: 'Hello, World!',

logMessage() {

console.log(this.message); // What is logged?

}

};

setTimeout(object.logMessage, 1000);


Expand answer

After a delay of 1 second, undefined is logged to console. Open the demo.

While setTimeout() function uses the object.logMessage as a callback, still, it inovkes object.logMessage as a regular function, rather than a method.

And during a regular function invocation this equals the global object, which is window in the case of the browser environment.

That's why console.log(this.message) inside logMessage method logs window.message, which is undefined.

Side challenge: how can you fix this code so that 'Hello, World!' is logged to console? Write your solution in a comment below!

Question 4: Artificial method

How can you call logMessage function so that it logs "Hello, World!"?


const object = {

message: 'Hello, World!'

};

function logMessage() {

console.log(this.message); // "Hello, World!"

}

// Write your code here...


Expand answer

There are at least 3 ways how to call logMessage() as a method on the object. Any of them is considered a correct answer:


const object = {

message: 'Hello, World!'

};

function logMessage() {

console.log(this.message); // logs 'Hello, World!'

}

// Using func.call() method

logMessage.call(object);

// Using func.apply() method

logMessage.apply(object);

// Creating a bound function

const boundLogMessage = logMessage.bind(object);

boundLogMessage();


Open the demo.

Question 5: Greeting and farewell

What logs to console the following code snippet:


const object = {

who: 'World',

greet() {

return `Hello, ${this.who}!`;

},

farewell: () => {

return `Goodbye, ${this.who}!`;

}

};

console.log(object.greet()); // What is logged?

console.log(object.farewell()); // What is logged?


Expand answer

'Hello, World!' and 'Goodbye, undefined!' are logged to console. Open the demo.

When calling object.greet(), inside the method greet() this value equals object because greet is a regular function. Thus object.greet() returns 'Hello, World!'.

But farewell() is an arrow function, so this value inside of an arrow function always equals this of the outer scope.

The outer scope of farewell() is the global scope, where this is the global object. Thus object.farewell() actually returns 'Goodbye, ${window.who}!', which evaluates to 'Goodbye, undefined!'.

Question 6: Tricky length

What logs to console the following code snippet:


var length = 4;

function callback() {

console.log(this.length); // What is logged?

}

const object = {

length: 5,

method(callback) {

callback();

}

};

object.method(callback, 1, 2);


Expand answer

4 is logged to console. Open the demo.

callback() is called using regular function invocation inside method(). Since this value during a regular function invocation equals the global object, this.length is evaluated as window.length inside callback() function.

The first statement var length = 4, being in the outermost scope, creates a property length on the global object: window.length becomes 4.

Finally, inside the callback() function this.length evaluates as window.length4 being logged to console.

Question 7: Calling arguments

What logs to console the following code snippet:


var length = 4;

function callback() {

console.log(this.length); // What is logged?

}

const object = {

length: 5,

method() {

arguments[0]();

}

};

object.method(callback, 1, 2);


Expand answer

3 is logged to console. Open the demo.

obj.method(callback, 1, 2) is invoked with 3 arguments: callback, 1 and 2. As result the arguments special variable inside method() is an array-like object of the following structure:


{

0: callback,

1: 1,

2: 2,

length: 3

}


Because arguments[0]() is a method invocation of callback on arguments object, this inside the callback equals arguments. As result this.length inside callback() is same as arguments.length — which is 3.

Summary

If you've answered correctly 5 or more questions, then you have a good understanding of this keyword!

Otherwise, you need a good refresher on this keyword. I recommend revising the post Gentle Explanation of "this" in JavaScript.

Ready for a new challenge? Try to solve the 7 Interview Questions on JavaScript Closures.