js implements bind

Simple implementation 

Function.prototype.bind = function(ctx,...res){
	const self = this;
	return function (...res2){
		self.apply(ctx,res.concat(res2))
	}
}

const fn = function(num){
	console.log(this.name+''+num)
}
fn(1)
fn.bind({name:'luen'})(1)

 

Official implementation, in order to deal with the case of using new to create objects


//官方实现
if (!Function.prototype.bind) {
    Function.prototype.bind = function (oThis) {
      if (typeof this !== "function") {
        // closest thing possible to the ECMAScript 5 internal IsCallable function
        throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
      }
 
      var aArgs = Array.prototype.slice.call(arguments, 1),
          fToBind = this,
          fNOP = function () {},
          fBound = function () {
            return fToBind.apply(this instanceof fNOP && oThis
                                   ? this
                                   : oThis || window,
                                 aArgs.concat(Array.prototype.slice.call(arguments)));
          };
 
      fNOP.prototype = this.prototype;
      fBound.prototype = new fNOP();
 
      return fBound;
    };
  }

 

Published 21 original articles · won praise 2 · Views 7283

Guess you like

Origin blog.csdn.net/qq_31261131/article/details/105469305
Recommended