细说apply、call和bind

apply、call和bind

我们可以使用函数对象的apply和call来应用函数,切换其执行上下文(this指针)。call和bind本质上是apply方法的语法糖。

call和apply

基本用法

略。

区别

二者的区别在于apply处上下文对象外,还接收一个数组做参数。而call则把数组换成了多个可选的形参。一般来说只传递上下文和一个形参时,推荐使用call以减少创建数组的损耗。令我,在严格模式下,如果不传第一个参数,那么this的值不会指向全局对象,而是undefined。

call的底层实现

Function.prototype.call = function (context) {
    var args = Array.prototype.slice.apply(arguments, [1]);
    return this.apply(context, args)
};

可以使用call或apply来实现继承 ###

 function Animal(name){   
    this.name = name;     
    this.showName = function(){   
        alert(this.name);     
    }     
}     
function Cat(name){ 
    Animal.call(this, name);    
}     
var cat = new Cat("Black Cat");  
cat.showName();

bind

bind(context[,pram1,pram2])。bind方法接收一个以上的参数,并返回一个新方法。该方法拥有和调用bind方法的函数一样的函数体,其执行上下文为bind方法的第一个参数,其形参为bind指定的其他参数。一个绑定函数也能使用new操作符创建对象:这种行为就像把原函数当成构造器。提供的 this 值被忽略,同时调用时的参数被提供给模拟函数。

基本用法

var student = {
    name : 'Joe',
    getInfo: function (id, clazz) {
        console.log(this.name+':'+id+":"+clazz);
    }
};

var person = {
    name: 'John Doe'
};

var foo = student.getInfo.bind(person);
foo(1101,'1班');

var bar = student.getInfo.bind(student,1102);
bar('2班')

实现原理

不考虑new作用的bind可以简化成:

Function.prototype.bind = function (context) {

    var func = this;
    var args = [].slice.apply(arguments, [1]);

    return function () {
        var argArr = [].slice.apply(arguments);
        func.apply(context, args.concat(argArr))
    };
};

MDN上给出了比较完善的版本,但也和具体实现不完全相同。

 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
                                 ? this
                                 : oThis || this,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();

    return fBound;
  };
}

偏函数

可以不指定bind的第一个参数,从而生成绑定了固定参数的偏函数

list.bind(undefined, 37)

配合setTimeout使用

默认情况下,在setTimeout中调用方法,this会指向全局对象,需要使用this显式的把上下文绑定到对象上。比如:

setTimeout(this.declare.bind(this), 1000);
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值