JS explicitly specifies the recipient of the function

Source: Internet
Author: User

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));    }}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.