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;
examp.forEach(json.jPush);
An error will be reported at this time:
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.
examp .forEach(json.jPush,json);
alert(json.jArray);//The result is normal, 123~456
There is another method:
examp.forEach(function (c) {
json.jPush( c);
});
alert(json.jArray);//123~456
You can also use bind
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