7 interview questions about JS this, how many can you answer correctly

7 interview questions about JS this, how many can you answer correctly

Preface

In JavaScript, this is the function calling context. It is precisely because the behavior of this is very complex that questions about this are always asked in JavaScript interviews.

The best way to prepare for an interview is to practice, so this article has compiled 7 interesting interviews for this keyword.

Note: The following JavaScript code runs in non-strict mode.

1: Variables and properties

What does the following code output:

const object = {
 message: 'Hello, World!',

 getMessage() {
 const message = 'Hello, Earth!';
 return this.message;
 }
};

console.log(object.getMessage()); // => ?

Answer:

Output: 'Hello, World!'

object.getMessage() is a method call, that's why this inside the method is equal to object.

There is also a variable declaration const message = 'Hello, Earth!' in the method, which does not affect the value of this.message.

2: Cat's name

What does the following code output:

function Pet(name) {
 this.name = name;

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

const cat = new Pet('Fluffy');

console.log(cat.getName()); // => ?

const { getName } = cat;
console.log(getName()); // =>?

Answer:

Output: 'Fluffy' and 'Fluffy'

When a function is called as a constructor ( new Pet('Fluffy') ), this inside the constructor is equal to the constructed object.

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

this.getName = () => this.name this.getName = () => this.name Creates the method getName on the constructed object. Because an arrow function is used, this in the arrow function is equal to this in the outer scope, which is the constructor Pet.

Calling cat.getName() and getName() returns the expression this.name, which evaluates to 'Fluffy'.

3: Delayed output

What does the following code output:

const object = {
 message: 'Hello, World!',

 logMessage() {
 console.log(this.message); // => ?
 }
};

setTimeout(object.logMessage, 1000);

Answer:

After a delay of 1 second, output: undefined

Even though the setTimeout() function uses object.logMessage as a callback, it still calls object.logMessage as a regular function rather than a method. And in a regular function call this is equal to the global object, which is window in a browser environment. That's why console.log(this.message) inside the logMessage method outputs window.message, which is undefined.

Challenge: How can you modify this code to output 'Hello, World!'? Write your solution in the comments below*

4: Complete the code

Complete the code so that the output is "Hello, World!".

const object = {
 message: 'Hello, World!'
};

function logMessage() {
 console.log(this.message); // => "Hello, World!"
}

// Write your code here...

Answer:

There are at least three ways to call logMessage() as a method on an object. Any of these are considered correct answers:

const object = {
 message: 'Hello, World!'
};

function logMessage() {
 console.log(this.message); // => 'Hello, World!'
}

// Using func.call() method logMessage.call(object);

// Using func.apply() method logMessage.apply(object);

// Use function binding const boundLogMessage = logMessage.bind(object);
boundLogMessage();

5. Greetings and Farewells

What does the following code output:

const object = {
 who: 'World',

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

 farewell: () => {
 return `Goodbye, ${this.who}!`;
 }
};

console.log(object.greet()); // => ?
console.log(object.farewell()); // => ?

Answer:

Output: 'Hello, World!' and 'Goodbye, undefined!'

When object.greet() is called, the value of this inside the greet() method is equal to object because greet is a regular function. So object.greet() returns 'Hello, World! '.

But farewell() is an arrow function, so the value of this in an arrow function is always equal to the this of the outer scope. The outer scope of farewell() is the global scope, where this is the global object. So object.farewell() actually returns 'Goodbye, ${window.who}!', which evaluates to 'Goodbye, undefined!'.

6: Tricky length

What does the following code output:

var length = 4;
function callback() {
 console.log(this.length); // => ?
}

const object = {
 length: 5,
 method(callback) {
 callback();
 }
};

object.method(callback, 1, 2);

Answer:

Output: 4

Call callback() using a regular function call inside method(). Because the value of this during a regular function call is equal to the global object, this.length is window.length inside the callback() function.

The first statement var length = 4 at the outermost level creates the property length on the global object, so window.length becomes 4.

Finally, inside the callback() function, the value of this.length is window.length, which outputs 4.

7: Calling parameters

What does the following code output:

var length = 4;
function callback() {
 console.log(this.length); // Output }

const object = {
 length: 5,
 method() {
 arguments[0]();
 }
};

object.method(callback, 1, 2);

Answer:

Output: 3

obj.method(callback, 1, 2) is called with 3 arguments: callback, 1, and 2. The arguments special variable inside the resulting method() is an array-like object with the following structure:

{
 0: callback,
 1: 1, 
 twenty two, 
 length: 3 
}

Because arguments[0]() is a method call on callback on the arguments object, this inside callback is equal to arguments. As a result, this.length and arguments.length inside callback() are the same, both are 3.

Summarize

If you get more than 5 correct, then you have a pretty good grasp of the this keyword.

This concludes this article about 7 JS this interview questions. For more relevant JS this interview questions, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of function classification and examples of this pointing in Javascript
  • Detailed explanation of this pointing problem in JavaScript function
  • Detailed explanation of this pointing problem in JavaScript
  • What is this in JavaScript point by point series
  • Detailed explanation of the this pointing problem in JavaScript

<<:  Solution to ERROR 1366 when entering Chinese in MySQL

>>:  How to manually upgrade the node version under CentOs

Recommend

A tutorial on how to install, use, and automatically compile TypeScript

1. Introduction to TypeScript The previous articl...

Summary of common commands for building ZooKeeper3.4 middleware under centos7

1. Download and decompress 1. Introduction to Zoo...

Docker custom network detailed introduction

Table of contents Docker custom network 1. Introd...

How to use xshell to connect to Linux in VMware (2 methods)

【Foreword】 Recently I want to stress test ITOO...

MySQL log trigger implementation code

SQL statement DROP TRIGGER IF EXISTS sys_menu_edi...

Usage of Linux userdel command

1. Command Introduction The userdel (user delete)...

Common styles of CSS animation effects animation

animation Define an animation: /*Set a keyframe t...

How to configure Openbox for Linux desktop (recommended)

This article is part of a special series on the 2...

WeChat applet picker multi-column selector (mode = multiSelector)

Table of contents 1. Effect diagram (multiple col...

Detailed explanation of the correct way to open em in CSS

Why do we say “usually 1em=16px”? The default tex...

Docker - Summary of 3 ways to modify container mount directories

Method 1: Modify the configuration file (need to ...

The top fixed div can be set to a semi-transparent effect

Copy code The code is as follows: <!DOCTYPE ht...

The process of installing MySQL 8.0.26 on CentOS7

1. First, download the corresponding database fro...