js中call,apply,bind用法

一、call 是 JavaScript 中函数对象的方法,用于调用函数并指定函数体内的 this 值。它的基本语法如下:
functionName.call(thisArg, arg1, arg2, ...);
  • functionName: 要调用的函数。
  • thisArg: 指定的 this 值,即在函数体内可以通过 this 访问的值。
  • arg1, arg2, ...: 要传递给函数的参数。
function greet(message) {
  console.log(message + ' ' + this.name);
}

const person = { name: 'John' };

// 使用 call 方法调用 greet 函数,并将 person 作为 this 值传递
greet.call(person, 'Hello');  // 输出: Hello John
二、apply用法基本等同于call ,与 call方法的区别在于,apply 方法的参数是以数组的形式传递的。 
function greet(message) {
  console.log(message + ' ' + this.name);
}

const person = { name: 'John' };

// 使用 apply 方法调用 greet 函数,并将 person 作为 this 值传递
greet.apply(person, ['Hello']);  // 输出: Hello John
三、bind用法,上述call,apply使用时候,程序立即执行,但是bind不然

bind 是 JavaScript 中函数对象的方法,它创建一个新的函数,该函数与调用 bind 的函数具有相同的函数体,但是在新函数中 this 的值是由 bind 的第一个参数指定的。同时,bind 方法也可以预先设置一些参数,这些参数在调用新函数时将作为原函数的前置参数传递。

newFunction = originalFunction.bind(thisArg[, arg1[, arg2[, ...]]]);
  • originalFunction: 要绑定上下文的原函数。
  • thisArg: 新函数中的 this 值。
  • arg1, arg2, ...: 可选的参数,预先设置给新函数的前置参数。
function greet(message) {
  console.log(message + ' ' + this.name);
}

const person = { name: 'John' };

// 使用 bind 创建一个新函数,其中 this 值为 person 对象
const greetPerson = greet.bind(person);

// 调用新函数
greetPerson('Hello');  // 输出: Hello John

另外,bind 方法也可以用于预先设置一些参数,例如:

function add(a, b) {
  return a + b;
}

// 创建一个新函数,将第一个参数预先设置为 2
const addTwo = add.bind(null, 2);

// 调用新函数,只需传递第二个参数
console.log(addTwo(3));  // 输出: 5

  • 8
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值