Because methods and values make no difference to the object's property values, it is easy to extract the object's method as a callback function directly to the higher order function. But it is also easy to forget that the recipient of the method should be explicitly specified. For example, a string buffer object uses an array to store strings.
var buffer = { entries: [], add: function(args) { this.entries.push(args); }, concat: function() { return this.entries.join(‘‘); }};var arr = [‘alert‘, ‘-‘, ‘123‘];// error: entries is undefinedarr.forEach(buffer.add);buffer.concat();
The recipient of the method depends on how it is called. The implementation of the Foreach method uses the global object as the default recipient. Because the global object does not have a entries property, this code throws an error.
To execute a method in a callback function
var arr = [‘alert‘, ‘-‘, ‘123‘];arr.forEach(function() { buffer.add(arr);});buffer.concat();
The method creates a display to invoke add () in the Buffer object method.
Returns a function of the specified recipient using bind ()
Creating a function to implement binding its recipient to a specified object is common.
arr = [‘alert‘, ‘-‘, ‘123‘];arr.forEach(buffer.add.bind(buffer));buffer.concat();
Note that bind () returns a new function instead of modifying the Buffer.add function. This means that the bind method is secure.
In fact, foreach () allows the caller to provide an optional parameter as the recipient of the callback function. Arr.foreach (buffer.add, buffer).
Compatible with browsers that do not implement the foreach () method
if(typeof Function.prototype.forEach !== ‘function‘) { Function.prototype.bind = function(context) { return this.apply(context, [].slice.call(arguments, 1)); }}