This article brings you code examples about the bind method in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
call, apply and new have been implemented before. By the way, bind is also implemented today.
First of all:
ok, the above code~
Function.prototype.mybind = function(context){ let that = this; let args1 = Array.prototype.slice.call(arguments,1); let bindFn = function(){ let args2 = Array.prototype.slice.call(arguments); return that.apply(this instanceof bindFn?this:context,args1.concat(args2)); } let Fn = function(){}; Fn.prototype = this.prototype; bindFn.prototype = new Fn(); return bindFn; }
First, get the first passed parameter args1, and intercept it here because the first parameter is this. Next, a function bindFn is declared, in which the second passed parameter args2 is obtained, and the execution of that is returned. The "that" here is the original function. Pay attention to judgment when executing the original function and binding the original function "this". If this is an instance produced by constructor bindFn new, then this here must be the instance itself. On the contrary, it is this(context) passed by the bind method. Finally, connect the parameters obtained twice through concat() and pass them in, thus realizing the first three items.
Last item: The properties and methods on the constructor are available on each instance. Here, an intermediate function Fn is used to connect the prototype chain. The prototype of Fn is equal to the prototype of this. Fn and this point to the same prototype object. The prototype of bindFn is equal to the instance of Fn. The __proto__ of the Fn instance points to Fn's prototype. That is, the prototype of bindFn points to the same prototype as this, pointing to the same prototype object. At this point, you have implemented your own bind method.
The code is written, let’s test it~
Function.prototype.mybind = function(context){ Let that = this; Let args1 = Array.prototype.slice.call(arguments,1); Let bindFn = function(){ Let args2 = Array.prototype.slice.call(arguments); return that.apply(this instanceof bindFn?this:context,args1.concat(args2)); } Let Fn = function(){}; Fn.prototype = this.prototype; bindFn.prototype = new Fn(); Return bindFn; } let obj = { name:'tiger' } function fn(name,age){ This.say = 'Woof woof~'; console.log(this); Console.log(this.name 'raised one' name ',' age 'years old'); } /**First time passing parameters*/ let bindFn = fn.mybind(obj,'
The above is the detailed content of Code example of bind method in JavaScript. For more information, please follow other related articles on the PHP Chinese website!