This article describes how to use bind to specify the receiver in javascript. For more information, see
The Code is as follows:
Var json = {
JArray: [],
JPush: function (c ){
This. jArray. push (c );
}
}
Var examp = ["123 ","~ "," 456 "];
Use the forEach loop examp given by ES5 and add them to jArray in json;
The Code is as follows:
Examp. forEach (json. jPush );
At this time, an error is reported:
The cause of 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 correct person for this.
Fortunately, forEach () provides a parameter specifically used to specify the object. view the code.
The Code is as follows:
Examp. forEach (json. jPush, json );
Alert (json. jArray); // The result is normal. Yes, 123 ~ 456
There is another method:
The Code is as follows:
Examp. forEach (function (c ){
Json. jPush (c );
});
Alert (json. jArray); // 123 ~ 456
Bind binding can also be used.
The Code is as follows:
Examp. 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 that of the original function. However, the receiver of the new function is the given object, while the receiver of the original function remains unchanged.
This means that the bind method is safe to use, because when a function or method is shared, you don't have to worry that the sharing method will not be modified.