JavaScript design pattern and open practice Learning (a) Function.prototype.bind

Source: Internet
Author: User

Use Function.prototype.bind to wrap the Func function

1, simplified version of BIND

function.prototype.bind=function  (context) {        var self=this//  Save the original function        return functions ()            {return  self.apply (context, arguments);        }    };     var obj={name: ' Seven '};     var func=function() {        alert (this. Name);    }. Bind (obj);    Func ();

2. Bind with Parameters

 function.prototype.bind=function   () {
    var  self=; Context  =[].shift.call (arguments); //  The this context that needs to be bound  args=[].slice.call (arguments); //         remaining arguments  return  function   () {  Self.apply (Context,[].concat.call (Args,[].slice.call (arguments)); 
//equal to return self.apply (context,args.concat (arguments)); parameters passed in after this arguments
var obj={name: ' Seven 'var func=function(a,b,c,d) {alert ( This . name); // output seven alert ([a,b,c,d]); // output [1,2,3,4] }. Bind (obj,1,2) func (3,4);

Note:

1) Arguments object: The arguments object is not an array and accesses a single parameter in the same way as an array element.

2) Shift usage: Used to remove the first element of the array and return the value of the first element.

2) Slice usage: the slice () method returns the selected element from an existing array.

3) concat usage: the concat () method is used to connect two or more arrays.

JavaScript design pattern and open practice Learning (a) Function.prototype.bind

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.