美文网首页
call,bind,apply

call,bind,apply

作者: Zoemings | 来源:发表于2017-10-11 15:41 被阅读18次

    前言

    虽然网上有许多关于此类的文章,但决定写一下自己的理解

    作用

    简而言之就是改变函数执行时的上下文,再具体一点就是改变函数运行时的this指向。
    例子:

    function Person(name) {
      this.name = name;
    }
    
    Person.prototype = {
      constructor: person,
      showName: function(){
        console.log(this.name);
      }
    }
    
    var person = new Person('Zoemings');
    person.showName();
    

    接下来

    var animal = {
      name: 'cat'
    }
    

    上面代码是一个对象字面量,没有所谓的showName方法,这时候,call,apply,bind可以帮我们干这件事

    // call
    person.showName.call(animal);
    // apply
    person.showName.apply(animal)
    // bind
    person.showName.bind(animal)();
    

    区别

    call apply与bind的差别

    call和apply改变了函数的this上下文后便执行该函数,而bind则属返回改变上下文后的一个函数

    call,apply的区别

    主要在于参数的区别,第一个参数都是改变上下文的对象,而call从第二个参数开始以参数列表的形式展示,apply则是把除了改变上下文对象的参数放在一个数组里面作为塔的第二个参数

    fn.call(obj, arg1, arg2, arg3....);
    fn.apply(obj, [arg1, arg2, arg3, ...])
    

    应用

    求数组中的最大值和最小值

    let arr = [1, 2, 3, 4, 5, 6, 7];
    
    Math.max.apply(Math, arr);
    Math.max.call(Math,1, 2, 3, 4, 5, 6, 7)
    
    Math.min.apply(Math, arr);
    Math.min.call(Math,1, 2, 3, 4, 5, 6, 7)
    

    将一个为数组转化为数组

    伪数组具有length属性,且可以通过下标的方式进行访问,但是没有push,pop等方法,我们可以利用call,apply将其转化为真正的数组便可以方便的使用数组方法了

    var arraryLike = {
      0: 'Mia',
      2: 'hangzhou',
      3: 'lovely' ,
      length: 4
    }
    

    上面就是一个对象字面量,将之转化为一个数组

    let arr =   Array.prototype.slice.call(arraryLike);
    
    • bind使用方法
    var unboundSlice = Arrary.prototype.slice;
    var slice = Function.prototype.apply.bind(unboundSlice);
    slice(arguments)
    

    利用apply和call做继承

    var Person = function (name, age){
      this.name = name;
      this.age = age;
    }
    
    var Girl = function (name) {
      Person.call(this, name);
    }
    
    var Boy = function (name, age){
      Person.apply(this, arguments)
    }
    
    var g1 = new Girl('miamia');
    var b1 = new Boy('miamia', 18)
    

    参考

    https://aotu.io/notes/2016/09/02/Different-Binding/?o2src=juejin&o2layout=compat
    http://www.cnblogs.com/coco1s/p/4833199.html

    相关文章

      网友评论

          本文标题:call,bind,apply

          本文链接:https://www.haomeiwen.com/subject/xfdwyxtx.html