JavaScript中call和apply函数方法

看下下面这个代码示例:

```javascript
const lufthansa = {
  airline: 'Lufthansa',
  iataCode: 'LH',
  bookings: [],
  book(flightNum, name) {
    console.log(
      `${name} booked a seat on ${this.airline} flight ${this.iataCode}${flightNum}`
    );
  },
};

lufthansa.book(239, ‘IT知识一享’);


```javascript
这段代码展示了一个名为 Lufthansa 的航空公司对象,其中包含了一些属性和方法。航空公司对象的名称是 Lufthansa,其 IATA 代码是 LH。

在这里插入图片描述

● 假如我们现在新增了一个航班,并且在外部重用函数,但是发现无法正常运行?

const lufthansa = {
  airline: 'Lufthansa',
  iataCode: 'LH',
  bookings: [],
  book(flightNum, name) {
    console.log(
      `${name} booked a seat on ${this.airline} flight ${this.iataCode}${flightNum}`
    );
    this.bookings.push({ flight: `${this.iataCode}${flightNum}`, name });
  },
};

lufthansa.book(239, 'IT知识一享');

const eurowings = {
  name: 'Eurowings',
  iataCode: 'EW',
  bookings: [],
};

const book = lufthansa.book;
book(23, 'IT知识一享2');

在这里插入图片描述

原因:
在 JavaScript 中,函数的 this 关键字指向调用该函数的对象。但是,当将一个函数从一个对象中提取出来并作为独立函数调用时,this 的指向会变化。
在代码中,将 lufthansa.book 赋值给 book 变量后,book 变量中的函数失去了与 lufthansa 对象的关联。因此,当你调用 book(23, ‘IT知识一享2’) 时,this 的指向变为全局对象(在浏览器中通常是 window 对象),而不是 lufthansa 对象。

现在就产生了问题,我们怎么样使得当我们想调用lufthansa对象时,this就指向lufthansa,而我们想调用eurowings时,this就指向eurowings呢?在JavaScript中,有三种函数方法可以做到这一点,分别是call、apply、bind;

call方法

首先我们先用call方法

const lufthansa = {
  airline: 'Lufthansa',
  iataCode: 'LH',
  bookings: [],
  book(flightNum, name) {
    console.log(
      `${name} booked a seat on ${this.airline} flight ${this.iataCode}${flightNum}`
    );
    this.bookings.push({ flight: `${this.iataCode}${flightNum}`, name });
  },
};

lufthansa.book(239, 'IT知识一享');

const eurowings = {
  airline: 'Eurowings',
  iataCode: 'EW',
  bookings: [],
};

const book = lufthansa.book;
book.call(eurowings, 666, 'IT知识一享2');
book.call(lufthansa, 888, 'IT知识一享3');

apply方法

我们重新创建一个航班来演示apply方法

const swiss = {
  airline: 'Swiss Air Lines',
  iataCode: 'LX',
  bookings: [],
};

const flightData = [999, 'IT知识一享999'];
book.apply(swiss, flightData);

在这里插入图片描述

但是在现代的JavaScript中,apply不建议使用,即使这种变量的方法,call方法也能使用

book.call(swiss, ...flightData);

在这里插入图片描述

总结:

call和apply比较:
相同之处:

  1. 两者都是用来调用函数并指定函数内部的 this 值。
  2. 两者都可以传递参数给被调用的函数。
    不同之处:
  3. 语法不同:call 方法接受一个指定的 this 值,后面是按参数列表传递的一系列参数;而 apply 方法接受一个指定的 this 值,后面是一个包含参数的数组或类数组对象。
  4. 参数传递方式不同:call 方法是按参数列表传递的,每个参数都需要单独列出;apply 方法是将参数放在一个数组或类数组对象中传递给函数。
  5. 性能差异:由于 apply 方法需要将参数打包成数组,因此在参数较多的情况下,使用 call 方法性能可能会更好。
  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值