JavaScript call()/apply()/bind()

call(), apply(), 和 bind() 都是 JavaScript 中用于调用函数的方法:

call()

call() 方法调用一个函数,其第一个参数是要设置为函数上下文的对象(也称为执行上下文),后续参数是传递给函数的参数列表。

语法:

function.call(thisArg, arg1, arg2, ...)
  • thisArg:函数执行时作为 this 的值。如果不需要指定 this,可以传入 null 或 undefined,此时全局对象将作为 this 的值(在浏览器中是 window 对象)。
  • arg1, arg2, ...:函数调用时传递的参数列表。
function greet(name) {
    return `Hello, ${name}! I'm ${this.role}.`;
}

const person = {
    role: 'developer'
};

console.log(greet.call(person, 'John'));
// Output: Hello, John! I'm developer.

apply()

apply() 方法与 call() 类似,区别在于它接收一个参数数组作为函数调用的参数

语法:

function.apply(thisArg, [argsArray])
  • thisArg:与 call() 方法中的作用相同,设置为函数上下文的对象。
  • argsArray:一个数组或类数组对象,其中的元素将作为参数传递给函数。
function greet(name, age) {
    return `Hello, ${name}! I'm ${this.role} and I'm ${age} years old.`;
}

const person = {
    role: 'developer'
};

console.log(greet.apply(person, ['John', 30]));
// Output: Hello, John! I'm developer and I'm 30 years old.

bind()

bind() 方法创建一个新的函数,称为绑定函数,它与原始函数具有相同的函数体,但 this 的值被预设为传递给 bind() 的第一个参数,其余参数作为绑定函数的参数供调用时使用。

语法:

function.bind(thisArg, arg1, arg2, ...)
  • thisArg:用来设置函数体内 this 的值。当绑定函数被调用时,传递的第一个参数将作为 this 的值。如果使用 new 操作符调用绑定函数,则忽略此值。
  • arg1, arg2, ...:当绑定函数被调用时,这些参数将置于实参之前传递给绑定函数。
function greet(name) {
    return `Hello, ${name}! I'm ${this.role}.`;
}

const person = {
    role: 'developer'
};

const greetPerson = greet.bind(person);
console.log(greetPerson('John'));
// Output: Hello, John! I'm developer.
  • call() 和 apply() 在函数调用时设置 this 的值,并立即执行该函数
  • bind() 返回一个新函数,并预设 this 的值,不会立即执行原函数
  • 8
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值