Home  >  Article  >  Web Front-end  >  How to use bind to specify the recipient in javascript_javascript tips

How to use bind to specify the recipient in javascript_javascript tips

WBOY
WBOYOriginal
2016-05-16 16:50:141087browse
Copy code The code is as follows:

var json = {
jArray: [],
jPush: function (c) {
this.jArray.push(c);
}
}
var examp = ["123", "~", "456"];

Use the forEach loop example given by ES5, and add them to the jArray in json;
Copy code The code is as follows:

examp.forEach(json.jPush);

An error will be reported at this time:
How to use bind to specify the recipient in javascript_javascript tips

is generated The reason for this error is that this in the json.jPush method does not point to the json object, but to the window. The way to solve this problem is to find the right person for this.
Fortunately, forEach() provides a parameter , specifically used to specify objects. See the code.
Copy code The code is as follows:

examp .forEach(json.jPush,json);
alert(json.jArray);//The result is normal, 123~456

There is another method:
Copy code The code is as follows:

examp.forEach(function (c) {
json.jPush( c);
});
alert(json.jArray);//123~456

You can also use bind
Copy code The code is as follows:

examp.forEach(json.jPush.bind(json));
alert(json.jArray) ;

bind creates a new function rather than modifying a function. The behavior of the new function is the same as that of the original function, but its receiver is the object we gave, and the original function The receiver remains unchanged.
This means that the use of the bind method is very safe, because when a function or method is shared, there is no need to worry that the shared method will not be modified.
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