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.fullName
person1.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天前赞一波!
相关文章
- 【说站】Python找回文子串的方法
- 【说站】php数组合并的方法
- 【说站】python json保存数据的方法
- 【说站】python系统内置方法如何获取
- 【说站】java反射三种方法
- 【说站】python字符串格式化的方法整理
- 【说站】python代码提速有哪些方法
- 【说站】python ElementTree解析的方法
- 【说站】python shutil有哪些操作文件的方法
- 【说站】java泛型方法的使用注意
- 【说站】java泛型方法的特征
- iOS 图片压缩方法的示例代码
- thinkphp怎么用u方法?ThinkPHP中U方法的使用浅析
- thinkphp怎么用model?ThinkPHP中实例Model方法的区别说明
- thinkPHP简单调用函数与类库的方法
- HTTP请求方法(HTTP Request Method)
- JS 字符串和数组相互转换
- JS 数组去重的多种方法
- JS 函数中的 arguments 类数组对象
- 介绍Js简单的递归排列组合
文章评论
评论问答