call() 方法

在JavaScript中,call() 方法用于调用一个函数,并将一个指定的 this 值和一个或多个参数传递给该函数。其语法如下:

function.call(thisArg, arg1, arg2, ...)
  • function:要调用的函数。
  • thisArg:在 function 函数运行时,指定的 this 值。如果不需要设置 this 值,可以传入 nullundefined
  • arg1, arg2, ...:要传递给 function 函数的参数。

call() 方法允许你在调用函数时指定函数体内 this 对象的值,从而可以用一个对象替换另一个对象。

例如:

const person = {
  fullName: function() {
    return this.firstName + " " + this.lastName;
  }
}

const person1 = {
  firstName: "John",
  lastName: "Doe"
}

const person2 = {
  firstName: "Mary",
  lastName: "Smith"
}

// 使用 call() 方法调用 fullName 函数,指定 this 为 person1
console.log(person.fullName.call(person1)); // 输出: John Doe

// 使用 call() 方法调用 fullName 函数,指定 this 为 person2
console.log(person.fullName.call(person2)); // 输出: Mary Smith

在上面的例子中,call() 方法允许我们在 fullName 函数内部使用 this 关键字来引用不同的对象,而不改变 fullName 函数本身的定义。

posted @   C羽言  阅读(28)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示