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

Echarts Basic Introduction: General Configuration of Bar Chart and Line Chart

1Basic steps of echarts Four Steps 1 Find the DOM...

HTML CSS3 does not stretch the image display effect

1. Use the transform attribute to display the ima...

Detailed explanation of how Vue components transfer values ​​to each other

Table of contents Overview 1. Parent component pa...

Summary of Spring Boot Docker packaging tools

Table of contents Spring Boot Docker spring-boot-...

Using the outline-offset property in CSS to implement a plus sign

Assume there is such an initial code: <!DOCTYP...

Detailed description of component-based front-end development process

Background <br />Students who work on the fr...

HTML Editing Basics (A Must-Read for Newbies)

Open DREAMWEAVER and create a new HTML. . Propert...

Vue3+el-table realizes row and column conversion

Table of contents Row-Column Conversion Analyze t...

Detailed explanation of the pitfalls of Apache domain name configuration

I have never used apache. After I started working...

An article to understand operators in ECMAScript

Table of contents Unary Operators Boolean Operato...

What is the function and writing order of the a tag pseudo class

The role of the a tag pseudo-class: ":link&qu...

Detailed graphic tutorial on how to enable remote secure access with Docker

1. Edit the docker.service file vi /usr/lib/syste...

How to migrate mysql storage location to a new disk

1. Prepare a new disk and format it with the same...