Function and arrows in this JS

Reprinted from: https://juejin.im/post/5aa1eb056fb9a028b77a66fd#heading-1

In the new ES6 JavaScript syntax function of the arrow, compared to the traditional function of the arrow function not only more compact, but it has been improved in this respect. As JavaScript in this relatively strange existence, many articles are not the same interpretation of this, this article attempts to clarify the relationship of this with the JS function.

A, written in function JS

1. Conventional writing function

Before ES6 grammar, function by function in JS keyword, params parameters and functions are braces wrapped body composition. In order to distinguish the arrow and function comes back, we put such a function is called a regular function, either with a conventional function of writing declarative style of writing assignments can also be used. example:

function Test (name) {   // declare formula writing 
    the console.log (name) 
} 
Test ( 'Jerry' ) 

the let test2 = function (name) {   // Assignment formula writing 
    the console.log (name) 
} 
test2 ( 'Tom')

2. The function of writing the arrow

Introducing ES6 arrow function, the function of writing become more concise, but in writing to follow certain rules.

Rule number one: use the arrow functions can only type of writing assignment, can not use declarative wording

const test = (name) => {
    console.log(name)
}
test('Jerry')

Rule 2: If only one parameter, you can not add parentheses, if not more than one parameter or parameters would need to add brackets

const test = name => {
    console.log(name)
}
test('Jerry')

const test2 = (name1, name2) => {
    console.log(name1 + ' and ' + name2)
}
test2('Tom', 'Jerry')

Rule number three: If the function body is only one sentence, you can not add braces

const test = name => console.log(name) 

Rule Four: If the body does not function parentheses, you can not write return, the arrow function will help you return

const add = (p1, p2) => p1 + p2
add(10, 25)

Remember: braces function body with the same keywords in return.

From the above examples we can see that the arrow function parentheses and curly braces regular functions are simplified. In addition to these simplifications, the arrows at the maximum for this function is that the conventional optimization function.

Second, conventional appreciated that this function

Before discussing the arrow function to optimize this, we come to understand exactly what this is, and how it is used. call this method using the first argument of the function is called, it can be changed during the function call, when the function is not called, the value of this can not be determined.

If you have not used the method to call a function call, then the above definition for this may not quite understand. So we need to understand both methods function calls.

1. Pure function calls
The first method is the most common, the following examples:
function Test (name) { 
    the console.log (name) 
    the console.log ( the this ) 
} 
Test ( 'Jerry')   // call the function

In this way we use the most, but this is just a shorthand method function call, it is complete wording such as the following:

function test(name) {
    console.log(name)
    console.log(this)
}
test.call(undefined, 'Tom')

Notes that the above method invocation call function yet? The first parameter method call received is this, where we pass an undefined . So, by definition, to break out after the execution of this function will be undefined it? No.

If you pass a context to null or undefined, then the window object is the default context (default context strict mode is undefined).

So here we break out of this is the Window object.

2. The object function call

Direct look at an example:

obj = const { 
    name: 'Jerry' , 
    the greet: function () { 
        the console.log ( the this .name) 
    } 
} 
obj.greet ()   // first call the method 
obj.greet.call (obj) // second kind of method invocation

The first example in calling the second method just call the method of syntactic sugar, the second method call is complete, and the second method is that it can be powerful to manually specify the this .

Examples of this manually specify:

obj = const { 
    name: 'Jerry' , 
    the greet: function () { 
        the console.log ( the this .name) 
    } 
} 
obj.greet.call ({name: 'Spike'})   // play out of the Spike

3. this constructor

Constructor of this a little bit special, each constructor will return an object after new, this object is this, that is, context context.

function Test() {
    this.name = 'Tom'
}
let p = new Test()
console.log(typeof p)  //object
console.log(p.name)    // Tom

() Calls a function 4. window.setTimeout () and window.setInterval

window.setTimeout () and window.setInterval () function of this somewhat special, which is this is the default window object.

Briefly summarize: The complete function call is to use the call method, including test.call(context, name) and obj.greet.call(context,name) , context here is that when the function is called context, is this, this is just this can be modified by the call method; constructor little bit special, it is an object of this return point directly after the new new; window.setTimeout() and window.setInterval() the default is to this window object.
 

Third, be understood that the function of this arrow

The above talked a lot about this, this is the first argument of the function call with the call method, but it can also be changed manually, so to determine the value of this is too much trouble. However, an arrow appears to us to determine the function of some help this busy.

1. The arrow of a function characteristic: this default binding layer

Mentioned above: the value of this can be modified by a method call, and only when we called to determine the value of this . And when we use the function of the arrow, the arrow function will help us to bind the outer layer of this default value, the arrow in the function and value of this this outer layer is the same.

Examples of functions without using the arrow:

obj = const { 
    A: function () {the console.log ( the this )}     
} 
obj.a ()   // play the object obj

Examples of the arrow using the function:

obj = const { 
    A: () => { 
        the console.log ( the this ) 
    } 
} 
obj.a ()   // play out of the window

In the case of using the arrow's function, because it would not use its own default function of this arrow, but will this be consistent and outer layers, the outermost layer of this is the window object.

2. The two arrows characteristic function: the inside can not be modified by this method call

This is also well understood, before we have been saying, this function can be manually specified with the call method, and in order to reduce the complexity of this, the arrow function can not be specified using this method call.

obj = const { 
    A: () => { 
        the console.log ( the this ) 
    } 
} 
obj.a.call ( '123')   // play result is still out of the window object

Because we said above window.setTimeout () function in where this is the default window, we can make it through this arrow and function of this layer is consistent:

the window.setTimeout () example:

obj = const { 
    A: function () { 
        the console.log ( the this ) 
        the window.setTimeout (() => { 
            the console.log ( the this ) 
        }, 1000 ) 
    } 
} 
obj.a.call (obj)   // first this is the object obj, this is the second object obj
Surely we understand, do not use the arrow functions obj.a function, because it's this or obj, and setTimeout function uses the arrow in the function, so it will be consistent and this outer layer, also obj; if a function in setTimeout use the arrow does not function, then it should be a break out of the window object.

this four, nested objects in multilayer function

Arrow function in the outer layer and this is consistent, but if the outer layer of several layers, and that it is consistent with what level it?

Directly on the examples:

obj = const { 
    A: function () {the console.log ( the this )}, 
    B: { 
        C: function () {the console.log ( the this )} 
    } 
} 
obj.a ()   // play object obj is quite in obj.a.call (obj) 
obj.bc () // play is obj.b object, the equivalent obj.bccall (obj.b)

The above code intuitive, obj.bc the next function corresponding to the function of the arrow into the following results:

obj = const { 
    A: function () {the console.log ( the this )}, 
    B: { 
        C: () => {the console.log ( the this )} 
    } 
} 
obj.a ()    // not function played using the arrow is obj 
obj.bc ()   // play is the window object! !

MDN official document which describes arrow function this defined time, described as "a function of the arrow does not create its own this, it will only inherit this one from their scope chain.", So the last example, play window the reason the object, the window object is that it is a layer of this, but just nested objects nested, nesting at this time there is no scope chain.

 

Guess you like

Origin www.cnblogs.com/lfri/p/11872696.html