6 This binding method in JavaScript

Source: Internet
Author: User

For most developers, the This keyword of JavaScript can cause a lot of trouble. Because JavaScript does not have a strict class model for languages such as Java, this point in the code is not clear unless you are dealing with callbacks.

In general, parts of the running code (not callbacks) bind the context of the function through the new keyword and some of the methods provided by Function.prototype, such as call/apply.

Problem

In each class, react uses this to point to the component itself, which can cause some problems for the developer. As in the react component, you may often see code similar to the following:

This.setstate ({loading:true});

Fetch ('/'). Then (function loaded () {
This.setstate ({loading:false});
});
The above code causes TYPEERROR because this.setstate is not a function. The reason for throwing typeerror is that when the promise callback is invoked, the internal context has changed, this points to the wrong object.

So, how do you properly bind this in your code?

Choose

Some of the 6 methods offered in this article are older technologies, others are for react, and some may not be supported by browsers, but they are worth exploring.

1. This alias
This approach is to create a variable at the top of the scope of the react component that points to this:

var component = this;
Component.setstate ({loading:true});

Fetch ('/'). Then (function loaded () {
Component.setstate ({loading:false});
});
This approach is convenient, easy to understand, and ensures that this points to the correct context.

2. Bind (This)
This is the way to inject this into the callback when the function is run, so that this in the callback points to the correct context:

This.setstate ({loading:true});

Fetch ('/'). Then (function loaded () {
This.setstate ({loading:false});
}.bind (this));
In JavaScript, all functions have a bind method that allows you to specify a specific value for this. Once the function is bound, the context cannot be overwritten, meaning that this will point to the correct context.

3, React Component Methods
When using React.createclass to define a component, react allows you to arbitrarily define a method in the class of this component, and this that is called in the method is automatically bound to the component itself:

React.createclass ({
Componentwillmount:function () {
This.setstate ({loading:true});

Fetch ('/'). Then (this.loaded);
},
Loaded:function loaded () {
This.setstate ({loading:false});
}
});
For components that are not very complex, this is a great way to resolve this point to the problem. In fact, if you use. Bind (this) in a component's method, react throws a warning:

Bind (): are binding a component to the component. React does this is for your automatically in a high-performance way and so can safely remove this call.
For ES2015 classes, however, automatic binding does not apply.

4. Arrow function
The ES2015 specification introduces an arrow function to make the definition of a function more concise. The arrow function implicitly returns a value, but more importantly, it is used in a closed scope:

This.setstate ({loading:true});

Fetch ('/'). Then (() => {
This.setstate ({loading:false});
});
This in the arrow function always points to the correct context, regardless of how many layers are nested, because this point in the function body is the object that is defined, not the object in which it is used. The downside, however, is that because the arrow function is not named, the stack information gives the tag the anonymous function when debugging.

If you use Babel to convert ES6 code into ES5 code, you'll find two interesting phenomena:

In some cases, the compiler can determine whether a function name is assigned to a variable
The compiler uses aliases to maintain the context
Const LOADED = () => {
This.setstate ({loading:false});
};

would be compiled to

var _this = this;
var loaded = function loaded () {
_this.setstate ({loading:false});
};
5, ES7 binding syntax
In ES7, there is a proposal for the BIND syntax, proposing:: As a new binding operator, the operator binds the left value and the right value (a function).

Take the implementation of map as an example:

function map (f) {
var mapped = new Array (this.length);

for (var i = 0; i < this.length; i++) {
Mapped[i] = f (this[i], i);
}

return mapped;
}
Unlike Lodash, we do not need to pass data to a map as an argument:

[1, 2, 3]::map (x => x * 2)
[2, 4, 6]
Are you familiar with the following code?

[].map.call (Somenodelist, MYFN);
Or
Array.from (somenodelist). Map (MYFN);
The ES7 binding syntax allows you to use a map as you would with an arrow function:

Somenodelist::map (MYFN);
It can also be used in react:

This.setstate ({loading:true});

Fetch ('/'). Then (this::() => {
This.setstate ({loading:false});
});
6. Method parameter designation
Some functions allow a definite value to be passed for this to ensure that it points to the correct context, for example, the map function takes this as the last argument:

Items.map (function (x) {
return <a onclick={this.clicked}>x</a>;
}, this);
Although the code can run, this is not a consistent implementation of the function. Most functions do not accept the this argument, so it is best to bind this by using the other methods above.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.