search
HomeWeb Front-endJS TutorialTips, working principles and precautions for using this keyword in JavaScript_javascript tips

To understand this according to its location, the situation can be roughly divided into three types:

1. In functions: this is usually an implicit parameter.

2. Outside the function (in the top-level scope): In the browser, this refers to the global object; in Node.js, it refers to the exports of the module.

 3. The string passed to eval(): If eval() is called directly, this refers to the current object; if eval() is called indirectly, this refers to the global object.

We have conducted corresponding tests for these categories:
1. this in the function

Functions can basically represent all callable structures in JS, so this is the most common scenario for using this, and functions can be divided into the following three roles:

Real function
Constructor
Method

 1.1 this

in real functions

In real functions, the value of this is a pattern that depends on the context in which it is found.

Sloppy mode: this refers to the global object (window in the browser).

Copy code The code is as follows:

function sloppyFunc() {
console.log( this === window); // true
}
sloppyFunc();

Strict mode: the value of this is undefined.

Copy code The code is as follows:

function strictFunc() {
'use strict' ;
console.log(this === undefined); // true
}
strictFunc();

this is an implicit parameter of the function, so its value is always the same. However, you can explicitly define the value of this by using the call() or apply() method.

Copy code The code is as follows:

function func(arg1, arg2) {
console .log(this); // 1
console.log(arg1); // 2
console.log(arg2); // 3
}
func.call(1, 2, 3); // (this, arg1, arg2)
func.apply(1, [2, 3]); // (this, arrayWithArgs)

1.2 this

in the constructor

You can use new to use a function as a constructor. The new operation creates a new object and passes this object into the constructor through this.

Copy code The code is as follows:

var savedThis;
function Constr() {
savedThis = this;
}
var inst = new Constr();
console.log(savedThis === inst); // true

The implementation principle of new operation in JS is roughly as shown in the following code (please see here for a more accurate implementation, this implementation is also more complicated):

Copy code The code is as follows:

function newOperator(Constr, arrayWithArgs) {
var thisValue = Object.create(Constr.prototype);
Constr.apply(thisValue, arrayWithArgs);
return thisValue;
}

1.3 this

in the method

The usage of this in methods is more inclined to traditional object-oriented languages: the receiver pointed to by this is the object that contains this method.

Copy code The code is as follows:

var obj = {
method: function () {
console.log(this === obj); // true
}
}
obj.method();

2. this in scope

In the browser, the scope is the global scope, and this refers to the global object (just like window):

Copy code The code is as follows:

<script><BR> console.log(this === window); // true<BR></script>

In Node.js, you usually execute functions in modules. Therefore, the top-level scope is a very special module scope:

Copy code The code is as follows:

// `global` (not `window`) refers to global object:
console.log(Math === global.Math); // true

// `this` doesn't refer to the global object:
console.log( this !== global); // true
// `this` refers to a module's exports:
console.log(this === module.exports); // true

3. this in eval()

eval() can be called directly (by calling the function name 'eval') or indirectly (called by other means, such as call()). For more details, see here.

Copy code The code is as follows:

// Real functions
function sloppyFunc() {
console.log(eval('this') === window); // true
}
sloppyFunc();

function strictFunc() {
'use strict ';
console.log(eval('this') === undefined); // true
}
strictFunc();

// Constructors
var savedThis;
function Constr() {
savedThis = eval('this');
}
var inst = new Constr();
console.log(savedThis === inst); / / true

// Methods
var obj = {
method: function () {
console.log(eval('this') === obj); // true
}
}
obj.method();

4. Traps related to this

You should be careful of the 3 traps related to this that will be introduced below. It should be noted that in the following examples, using Strict mode can improve the security of the code. Since in real functions, the value of this is undefined, you will get a warning when something goes wrong.

 4.1 Forgot to use new

If you are not using new to call the constructor, then you are actually using a real function. Therefore this will not be the value you expected. In Sloppy mode, this points to window and you will create global variables:

Copy code The code is as follows:

function Point(x, y) {
this .x = x;
this.y = y;
}
var p = Point(7, 5); // we forgot new!
console.log(p === undefined) ; // true

// Global variables have been created:
console.log(x); // 7
console.log(y); // 5

However, if you are using strict mode, you will still get a warning (this===undefined):

Copy code The code is as follows:

function Point(x, y) {
' use strict';
this.x = x;
this.y = y;
}
var p = Point(7, 5);
// TypeError: Cannot set property ' x' of undefined

4.2 Improper use of methods

If you directly get the value of a method (not call it), you are using the method as a function. You'll probably do this when you want to pass a method as a parameter into a function or a calling method. This is the case with setTimeout() and registered event handlers. I will use the callIt() method to simulate this scenario:

Copy code The code is as follows:

/**Similar to setTimeout() and setImmediate()*/
function callIt(func) {
func();
}

If you call a method as a function in Sloppy mode, *this* points to the global object, so all subsequent creations will be global variables.

Copy code The code is as follows:

var counter = {
count: 0,
// Sloppy-mode method
inc: function () {
this.count ;
}
}
callIt(counter.inc);

// Didn't work:
console.log(counter.count); // 0

// Instead, a global variable has been created
// (NaN is result of applying to undefined):
console.log(count); // NaN

If you do this in Strict mode, this is undefined, and you still won’t get the desired result, but at least you will get a warning:

Copy code The code is as follows:

var counter = {
count: 0,
// Strict-mode method
inc: function () {
'use strict';
this.count ;
}
}
callIt(counter.inc);

// TypeError: Cannot read property 'count' of undefined
console.log(counter.count);

To get the expected results, you can use bind():

Copy code The code is as follows:

var counter = {
count: 0,
inc: function () {
this.count ;
}
}
callIt(counter.inc.bind(counter));
// It worked!
console .log(counter.count); // 1

bind() creates another function that always sets the value of this to counter.

 4.3 Hide this

When you use a function in a method, you often forget that the function has its own this. This this is different from the method, so you cannot mix the two this together. For details, please see the following code:

Copy code The code is as follows:

var obj = {
name: 'Jane' ,
friends: [ 'Tarzan', 'Cheeta' ],
loop: function () {
'use strict';
this.friends.forEach(
function (friend) {
            console.log(this.name ' knows ' friend);
                              ; Cannot read property 'name' of undefined



In the above example, this.name in the function cannot be used because the value of this in the function is undefined, which is different from this in the method loop(). Three ideas are provided below to solve this problem:

1. that=this, assign this to a variable, so that this is explicitly displayed (in addition to that, self is also a very common variable name used to store this), and then use that Variable:

Copy code

The code is as follows:loop: function () { 'use strict '; var that = this;
this.friends.forEach(function (friend) {
console.log(that.name ' knows ' friend);
});
}



2. bind(). Use bind() to create a function whose this always contains the value you want to pass (in the example below, the this of the method):

Copy code

The code is as follows:loop: function () { 'use strict '; this.friends.forEach(function (friend) {
console.log(this.name ' knows ' friend);
}.bind(this));
}

3. Use the second parameter of forEach. The second parameter of forEach will be passed into the callback function and used as this of the callback function.

Copy code The code is as follows:

loop: function () {
'use strict ';
this.friends.forEach(function (friend) {
console.log(this.name ' knows ' friend);
}, this);
}

5. Best Practices

Theoretically, I think real functions do not have their own this, and the above solution is also based on this idea. ECMAScript 6 uses arrow functions to achieve this effect. Arrow functions are functions that do not have their own this. In such a function, you can use this casually, and you don't have to worry about whether it exists implicitly.

Copy code The code is as follows:

loop: function () {
'use strict ';
// The parameter of forEach() is an arrow function
this.friends.forEach(friend => {
// `this` is loop's `this`
console.log (this.name ' knows ' friend);
});
}

I don’t like that some APIs treat this as an additional parameter of the real function:

Copy code The code is as follows:

beforeEach(function () {
this.addMatchers ({
toBeInRange: function (start, end) {
...
} });
});

Write an implicit parameter as explicit and pass it in, the code will be easier to understand, and this is consistent with the requirements of the arrow function:

Copy code The code is as follows:
beforeEach(api => {
api. addMatchers({
             toBeInRange(start, end) {                                                                                                  
Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!