js自己实现 bind

简单实现 

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)

官方实现,为了处理使用new来创建对象的情况


//官方实现
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;
    };
  }
发布了21 篇原创文章 · 获赞 2 · 访问量 7283

猜你喜欢

转载自blog.csdn.net/qq_31261131/article/details/105469305
今日推荐