JavaScript中的 "call/apply"简介

96 阅读2分钟

在 JavaScript 中,可以使用 "call" 和 "apply" 方法来调用一个函数,并且可以设置函数中 "this" 的值以及传递参数。

call 方法

"call" 方法用于调用一个函数,可以将一个对象作为参数传递给该函数,并且该函数中的 "this" 将会被设置为传递的对象。除了第一个参数之外,"call" 方法接受一个或多个参数,这些参数将会被传递给函数。

下面是一个使用 "call" 方法的示例:

let person = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
let person1 = {
  firstName:"John",
  lastName: "Doe"
}
let person2 = {
  firstName:"Mary",
  lastName: "Doe"
}

// 调用 person 对象的 fullName 方法,并将 person1 对象传递给该方法
console.log(person.fullName.call(person1)); // 输出 "John Doe"

// 调用 person 对象的 fullName 方法,并将 person2 对象传递给该方法
console.log(person.fullName.call(person2)); // 输出 "Mary Doe"

在上面的示例中,我们定义了一个 "person" 对象,该对象有一个 "fullName" 方法,该方法返回 "firstName" 和 "lastName" 的组合。我们创建了两个不同的对象 "person1" 和 "person2",并将它们作为参数传递给 "fullName" 方法。

apply 方法

"apply" 方法与 "call" 方法类似,不同之处在于它接受一个数组作为第二个参数,该数组包含要传递给函数的参数。在使用 "apply" 方法时,我们可以使用 "arguments" 对象来传递任意数量的参数。

下面是一个使用 "apply" 方法的示例:

let person = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}
let person1 = {
  firstName:"John",
  lastName: "Doe"
}
let person2 = {
  firstName:"Mary",
  lastName: "Doe"
}

// 调用 person 对象的 fullName 方法,并将 person1 对象作为第一个参数,以及一个字符串作为第二个参数
console.log(person.fullName.apply(person1, ["Hello"])); // 输出 "John Doe"

// 调用 person 对象的 fullName 方法,并将 person2 对象作为第一个参数,以及两个字符串作为第二个参数
console.log(person.fullName.apply(person2, ["Hello", "World"])); // 输出 "Mary Doe"

在上面的示例中,我们将 "person1" 和 "person2" 对象作为第一个参数传递给 "fullName" 方法,并使用一个数组作为第二个参数来传递额外的参数。

使用 "call" 和 "apply" 方法可以让我们更方便地调用函数,并且可以设置函数中 "this" 的值以及传递参数。