js bind的实现

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

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

看到一个关于美团面试题是如何实现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能够更简洁:app

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也能够省略了。this

相关文章
相关标签/搜索