The code copy is as follows:
var json = {
jArray: [],
jPush: function (c) {
this.jArray.push(c);
}
}
var test = ["123", "~", "456"];
Use the forEach given by ES5 to loop the example, and add them to jArray in json;
The code copy is as follows:
test.forEach(json.jPush);
An error will be reported at this time:
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 solution to this problem is to find the right person for this.
Fortunately, forEach() provides a parameter specifically for specifying objects. See the code.
The code copy is as follows:
test.forEach(json.jPush,json);
alert(json.jArray);//The result is normal, 123~456
There is another method:
The code copy is as follows:
test.forEach(function (c) {
json.jPush(c);
});
alert(json.jArray);//123~456
You can also use bind to bind
The code copy is as follows:
test.forEach(json.jPush.bind(json));
alert(json.jArray);
bind creates a new function instead of modifying a function. The behavior of the new function is the same as the original function, but its receiver is the object we give, while the receiver of the original function remains unchanged.
This means that the use of 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.