Copy Code code as follows:
var json = {
Jarray: [],
Jpush:function (c) {
This.jArray.push (c);
}
}
var examp = ["123", "~", "456"];
Use the foreach loops given by ES5 to examp them and add them to the Jarray in JSON;
Copy Code code as follows:
Examp.foreach (Json.jpush);
This time will be an error:
This error is caused because this in the Json.jpush method does not point to the JSON object, but to window. The way to solve this problem is to find the right person for this one.
Fortunately foreach () provides a parameter specifically for the specified object. Look at the code.
Copy Code code as follows:
Examp.foreach (Json.jpush,json);
Alert (Json.jarray)//The result is normal, 123~456.
There is another way:
Copy Code code as follows:
Examp.foreach (function (c) {
Json.jpush (c);
});
alert (json.jarray);//123~456
You can also use bind bind
Copy Code code as follows:
Examp.foreach (Json.jPush.bind (JSON));
alert (Json.jarray);
Bind creates a new function instead of modifying a function. The new function behaves the same as the original function, but his receiver is the given object and the receiver of the original function remains unchanged.
This means that the use of the bind method is very safe because a function or method is shared without fear that the shared method will not be modified.