美文网首页
Apply && Call

Apply && Call

作者: 懂会悟 | 来源:发表于2020-09-09 08:43 被阅读0次

    1、apply(), call()

    • obj.call(thisObj, arg1, arg2, ...)
    • obj.apply(thisObj, [arg1, arg2, ...])

    apply,call两者作用一致,都是把obj(即this)绑定到thisObj,这时候thisObj具备了obj的属性和方法。或者说thisObj继承了obj的属性和方法。绑定后会立即执行函数。唯一区别是apply接受的是数组参数,call接受的是连续参数。

    function add(j,k) {
        return j + k;
    }
    
    function sub (j,k) {
        return j - k;
    }
    
    
    add(5,3)
    // 8
    sub.call(add, 5,3)
    // 2
    sub.apply(add, [5,3])
    // 2
    add.call(sub, 5,3)
    // 8
    add.apply(sub, [5,3])
    // 8
    
    // 调用原生对象的方法
    
    let a = { 0:1, 1:"y", length: 2 }
    
    a.slice()
    // TypeError: a.slice is not a function
    
    Array.prototype.slice.call(a)
    // [1, "y"]
    
    // 实现继承
    let Parent = function () {
        this.name = 'tom',
        this.age = 22
    }
    
    let Child = {}
    console.log(Child)
    // {}空对象
    
    Parent.call(Child)
    console.log(Child)
    // {name: 'tom', age: 22}
    

    相关文章

      网友评论

          本文标题:Apply && Call

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