Javascrip中call和apply的用途

127 阅读1分钟

  • 改变this的指向 var obj1 = { name:'seven' } var obj2 = { name:'name' } window.name = 'window'; var getName = function(){ console.log(this.name); };

    getName() // output window
    getName.call(obj1) // output seven
    getName.call(obj2) // output name
    
  • Function.prototype.bind Function.prototype.bind = function(context){ var self = this; // save the origin function context return function(){ // return new function return self.apply(context,arguments); // use context replace the new function this } }

    var obj = {
      name:'name'
    }
    
    var func = function(){
      console.log(this.name);
    }.bind(obj);
    
    func(); // name
    

    优化版本的bind Function.prototype.bind = function(){ var _this = this, context = [].shift.call(arguments), // 获取传入的运行环境 args = [].slice.call(arguments); // 获取第一次传入的参数

    	return function(){
    		return _this.apply(context,[].concat.call(args,[].slice.call(arguments)));
    	}
    }
    
    var obj = {
    	name:'name'
    }
    
    var func = function(a,b,c,d){
    	console.log(this.name);
    	console.log([a,b,c,d]);
    }.bind(obj,12,23);
    
    func(34,45);
    
  • 借用其他对象的方法 Array.prototype.slice.call(arguments)比如这个最常见的转换arguments为数组的hack写法就是一种借用Array的slice方法来转换arguments。