Home  >  Article  >  Web Front-end  >  Tips, working principles and precautions for using this keyword in JavaScript_javascript tips

Tips, working principles and precautions for using this keyword in JavaScript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:47:301476browse

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