雷达智富

首页 > 内容 > 程序笔记 > 正文

程序笔记

JS 的 apply 方法

2024-10-03 20

1. 前言2. 改变 this 指向3. 将数组入参变为一般入参

1. 前言


apply() 的作用有两个: 1. 改变 this 指向 2. 将数组入参变为一般入参

刚开始看到 apply() 时,对它的用法非常模糊,而且不易理解,通过查找相关文章,才慢慢的明白它的妙用

2. 改变 this 指向


相信在网上查找 apply() 用法时,都会看到下面这段代码,首次运行,看到输出的结果,我是懵逼的

var person = {    fullName: function () {        return this.firstName + " " + this.lastName;    }}var person1 = {    firstName: "Bill",    lastName: "Gates",}const res = person.fullName.apply(person1)console.log(res); // Bill Gates

如何理解 apply() 这段代码 ?

person.fullName() 调用 this.firstName 和 this.lastName 这两个属性,this 指向 person,但它没有这两个属性

使用 apply() 方法可以改变 this 的指向,将 this 的指向改为 person1,所以 person.fullName() 方法就可以成功访问到 this.firstName 和 this.lastName 这两个属性的值了

person.fullName.apply(person1) 可以理解为下面代码,但不要这么写,本质不一样

person1.fullName = person.fullNameperson1.fullName()

3. 将数组入参变为一般入参


Math.max() 举例

// 正确用法Math.max(1, 2, 3)// 错误用法Math.max([1, 2, 3])

使用 apply() 的第二个参数将数组入参变为一般入参

注意,这里的第一个参数值为 null,也就是没有改变 this 的指向

Math.max.apply(null, [1, 2, 3])
更新于:15天前
赞一波!

文章评论

评论问答