zoukankan      html  css  js  c++  java
  • 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也可以省略了。

      

      

     

     

  • 相关阅读:
    python3获取文件夹大小
    git master分支被污染,dev是最新稳定的
    优化经验杂记
    kong
    prometheus
    C# 线程执行带参方法的几种写法(ThreadStart,delegate (),()=>)
    MySql字符集utf8mb4和utf8区别
    程序员必备的一些数学基础知识
    hbase统计表的行数的三种方法
    Flink实时计算pv、uv的几种方法
  • 原文地址:https://www.cnblogs.com/hjj2ldq/p/9566150.html
Copyright © 2011-2022 走看看