javascript apply的作用和用法

半兽人 发表于: 2025-02-06   最后更新时间: 2025-02-06 12:07:41  
{{totalSubscript}} 订阅, 221 游览

apply() 是 JavaScript 函数对象的一个方法,它的作用是调用一个函数,并且改变它的 this 指向,同时以数组形式传递参数


1. 语法

func.apply(thisArg, [argsArray])
  • func:要调用的函数。
  • thisArg:执行 func 时绑定的 this 值(可以是 nullundefined,此时 this 指向全局对象)。
  • [argsArray]:一个数组或类数组对象,作为 func 的参数列表。

2. 基本用法

(1)改变 this 指向

function greet(name) {
    console.log(this.message + ', ' + name);
}

const obj = { message: 'Hello' };
greet.apply(obj, ['Tom']); // 输出:Hello, Tom

this 指向 obj,所以 greet 里的 this.message 变成 obj.message


(2)应用于内置方法

apply()Math.max 计算数组的最大值

const numbers = [3, 5, 9, 1, 6];
console.log(Math.max.apply(null, numbers)); // 9

等价于:

console.log(Math.max(...numbers)); // 9  (ES6 扩展运算符)

(3)借用别的对象的方法

apply() 借用 Array.prototype.slice

function convertToArray() {
    return Array.prototype.slice.apply(arguments);
}
console.log(convertToArray(1, 2, 3)); // [1, 2, 3]

🔹 arguments 是类数组对象,不能直接用 slice(),但 apply() 让它变成真正的数组。


(4)用 apply() 实现继承

function Parent(name) {
    this.name = name;
}
function Child(name, age) {
    Parent.apply(this, [name]); // 借用 Parent 的构造函数
    this.age = age;
}

const child = new Child('Tom', 5);
console.log(child.name, child.age); // Tom 5

apply()Child 继承 Parent 的属性。


3. apply() vs call()

方法 作用 参数格式
apply() 改变 this 并调用函数 func.apply(thisArg, [argsArray])
call() 改变 this 并调用函数 func.call(thisArg, arg1, arg2, ...)

示例

function add(a, b) {
    return a + b;
}
console.log(add.apply(null, [2, 3])); // 5
console.log(add.call(null, 2, 3)); // 5

apply() 用数组传参,call() 直接传入多个参数。


4. apply() vs bind()

方法 作用 是否立即执行
apply() 绑定 this 并调用函数 立即执行
bind() 绑定 this 并返回新函数 不立即执行

示例

function greet(name) {
    console.log(this.message + ', ' + name);
}

const obj = { message: 'Hello' };

const boundFunc = greet.bind(obj);
boundFunc('Tom'); // Hello, Tom

greet.apply(obj, ['Tom']); // 立即执行:Hello, Tom

5. 总结

apply() 主要作用:

  • 改变 this 指向,使函数在指定对象上执行。
  • 调用函数,参数以数组(或类数组)形式传入。
  • 借用方法,如 Array.prototype.slice.apply(arguments) 把类数组转换成数组。
  • 继承,在构造函数中 apply() 让子类继承父类的属性。
  • 配合 Math.max() 处理数组最大值 Math.max.apply(null, arr)

核心区别

  • apply(this, [argsArray])数组传参,立即执行
  • call(this, arg1, arg2, ...)逐个传参,立即执行
  • bind(this, arg1, arg2, ...)返回新函数,不立即执行
更新于 2025-02-06
在线,1小时前登录

查看javascript更多相关的文章或提一个关于javascript的问题,也可以与我们一起分享文章