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

Windows Server 2008 Tutorial on Monitoring Server Performance

Next, we will learn how to monitor server perform...

Html makes a simple and beautiful login page

Let’s take a look first. HTML source code: XML/HT...

Solution to the failure of docker windows10 shared directory mounting

cause When executing the docker script, an error ...

Detailed explanation of JavaScript error capture

Table of contents 1. Basic usage and logic 2. Fea...

MySQL InnoDB monitoring (system layer, database layer)

MySQL InnoDB monitoring (system layer, database l...

Use of Vue3 table component

Table of contents 1. Ant Design Vue 1. Official w...

Use nexus as a private library to proxy docker to upload and download images

1. Nexus configuration 1. Create a docker proxy U...

Detailed explanation of JS homology strategy and CSRF

Table of contents Overview Same Origin Policy (SO...

Mysql stores tree structure through Adjacency List (adjacency list)

The following content introduces the process and ...

Detailed explanation of fuser command usage in Linux

describe: fuser can show which program is current...

HTML Several Special Dividing Line Effects

1. Basic lines 2. Special effects (the effects ar...

Nginx configuration SSL and WSS steps introduction

Table of contents Preface 1. Nginx installation 1...

MySQL 5.7.30 Installation and Upgrade Issues Detailed Tutorial

wedge Because the MySQL version installed on the ...

Docker completely deletes private library images

First, let’s take a look at the general practices...