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