js bind的实现

call,apply,bind都是用来挟持对象或者说更改this指向的,但是区别还是有的,call 传参是 fn.call(this,1,2,3) apply传参是 fn.apply(this,[1,2,3])

而前两者是立即执行的,后者Bind是返回一个函数 var foo = fn.bind(this)  foo()

看到一个关于美团面试题是如何实现js bind

      if (typeof Function.prototype.bind === "undefined"){
	  Function.prototype.bind = function (thisArgs){
	    var fn = this,
	        slice = Array.prototype.slice,
	        args = slice.call(arguments, 1);//都是为了截取参数
	    return function (){
	      return fn.apply(thisArgs, args.concat(slice.call(arguments)));
	    }
	  }
	}

代码来自书籍 《javaScript 模式》

其实结合上ES6可以更简洁:

Function.prototype.bind1 = function (thisArgs){
	var fn = this,//foo
	//arguments 是类数组,支持for循环,但不支持数组的方法
//	args = [].slice.call(arguments, 1);//截取参数 5
	args = Array.from(arguments).slice(1);//截取参数 5
	return function (){
	   return fn.apply(thisArgs,args);
	}
}
	var m = {	
  	  "x" : 1
	};
	function foo(y) {	
    	console.log(this.x + y);
	}
//	foo.apply(m, [5]);
//	foo.call(m, 5);
	var foo1 = foo.bind1(m,5);
	foo1();

上面的return函数也换成箭头函数的话就更加简洁了。

 

Function.prototype.bind1 = function (thisArgs){
  args = Array.from(arguments).slice(1);//截取参数 5
  return ()=>this.apply(thisArgs,args)
}

 

箭头函数注意:只有一句的时候可以省略return,然后前面的fn也可以省略了。

 

  

  

 

 

posted @ 2018-08-31 15:41  萝卜爱吃青菜  阅读(378)  评论(0编辑  收藏  举报