call apply bind的理解使用。

call apply bind 三者作用是改变某个函数的执行上下文(Execution Context),具体作用是改变函数体内部this的指向。

bind:
MDN

function.bind(thisArg[, arg1[, arg2[, …]]])

bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind()
的第一个参数,而其余参数将作为新函数的参数,供调用时使用。、

参数:

thisArg:调用绑定函数时作为 this 参数传递给目标函数的值。 如果使用new运算符构造绑定函数,则忽略该值。当使用 bind 在
setTimeout 中创建一个函数(作为回调提供)时,作为 thisArg 传递的任何原始值都将转换为 object。如果 bind
函数的参数列表为空,或者thisArg是null或undefined,执行作用域的 this 将被视为新函数的 thisArg。

arg1, arg2, …

当目标函数被调用时,被预置入绑定函数的参数列表中的参数。

mdn代码示例

const module = {
  x: 42,
  getX: function() {
    return this.x;
  }
};

const unboundGetX = module.getX;
console.log(unboundGetX()); 
// The function gets invoked at the global scope
// expected output:  
const boundGetX = unboundGetX.bind(module);
console.log(boundGetX());

解释:
const boundGetX = unboundGetX.bind(module);

  1. unboundGetX 复制了getX函数
  2. 绑定module为此函数的this
  3. 通过this访问module的东西。
  4. 返回函数(返回一个原函数的拷贝,并拥有指定的 this 值和初始参数。)

应用:

在默认情况下,使用 window.setTimeout() 时,this 关键字会指向 window (或
global)对象。当类的方法中需要 this 指向类的实例时,你可能需要显式地把 this 绑定到回调函数,就不会丢失该实例的引用。


apply:
MDN

func.apply(thisArg, [argsArray])

apply() 方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数。

var pokemon = {
    firstname: 'Pika',
    lastname: 'Chu ',
    getPokeName: function() {
        var fullname = this.firstname + ' ' + this.lastname;
        return fullname;
    }
};

var pokemonName = function(snack, hobby) {
    console.log(this.getPokeName() + ' loves ' + snack + ' and ' + hobby);
};

pokemonName.call(pokemon,'sushi', 'algorithms'); 
// Pika Chu  loves sushi and algorithms
pokemonName.apply(pokemon,['sushi', 'algorithms']); 
// Pika Chu  loves sushi and algorithms

call:
MDN

function.call(thisArg, arg1, arg2, …)

bind()和call()之间的主要区别在于call()方法:

  1. 接受其他参数
  2. 执行它立即调用的函数。
  3. call()方法不会复制正在调用它的函数。

call()和apply()用于完全相同的目的。它们之间的唯一区别是_ call()期望所有参数都单独传递,而apply()需要一个数组。例:

bind只是修改了this指向,而call与apply是修改this指向并且执行了

let obj = {
    name: 'kobe'
};

function showName () {
    console.log(this.name);
}

let testFunc = showName.bind(obj);
testFunc();

//  showName.call(obj) 
//  showName.bind(obj)();等价

参考:MDN
https://segmentfault.com/a/1190000017462138

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值