细说apply、call和bind

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Hukaihe/article/details/65629222

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);

猜你喜欢

转载自blog.csdn.net/Hukaihe/article/details/65629222
今日推荐