3

JavaScript apply() 方法

 1 year ago
source link: https://www.myfreax.com/javascript-apply-method/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
JavaScript apply() 方法

JavaScript apply() 方法

在本教程中,您将了解类型JavaScript  Functionapply() 方法以及如何有效地使用它。

JavaScript apply()方法介绍

Function.prototype.apply() 方法允许使用指定的 this 值和一个类数组对象的参数调用函数。下面是 apply() 方法的语法:

fn.apply(thisArg, [args]); 

apply() 方法接受两个参数:

  • thisArg 是为调用 fn 函数提供 this 的值。
  • args 是一个数组参数,指定函数的参数 fn。从 ES5 开始,args 参数可以是类数组对象或数组对象。

apply() 方法与 call() 方法类似,只是它将函数的参数作为数组而不是每个参数都都单独传递。

JavaScript apply() 方法示例

让我们举一些使用 apply() 方法的例子。

简单的 JavaScript apply() 方法示例

假设你有一个person对象:

const person = {
    firstName: 'John',
    lastName: 'Doe'
}

和一个命名为 greet() 的函数,如下:

function greet(greeting, message) {
    return `${greeting} ${this.firstName}. ${message}`;
}

greet() 函数接受两个参数:greetingmessage。在 greet() 函数内部,我们引用了一个对象,该对象有 firstName 属性。

下面的示例展示如何使用 apply() 方法调用 greet() 函数并设置 greet() 函数的 this 值为 person对象:

let result = greet.apply(person, ['Hello', 'How are you?']);

console.log(result);
Hello John. How are you?

在这个例子中,我们使用 apply() 方法将 greet() 函数内部的 this 值设置为 person 对象。函数的参数作为数组传递给 greet() 方法 。

apply()方法调用了greet()函数,并将this值设置为person对象并将参数设置为数组['Hello', 'How are you?']

如果使用 call() 方法,则需要单独传递  greet()  函数的参数,如下所示:

let result = greet.call(person, Hello', 'How are you?');

apply() 方法允许一个对象借用另一个对象的方法,在不复制粘帖代码的情况下。

假设您有computer 对象:

const computer = {
    name: 'MacBook',
    isOn: false,
    turnOn() {
        this.isOn = true;
        return `The ${this.name} is On`;
    },
    turnOff() {
        this.isOn = false;
        return `The ${this.name} is Off`;
    }
};

server 对象:

const server = {
    name: 'Dell PowerEdge T30',
    isOn: false
};
Code language: JavaScript (javascript)

server 对象没有 turnOn()turnOff() 方法。

要在 server 对象上执行  computer 对象 turnOn() 的方法,可以像下面这样使用 apply() 方法:

let result = computer.turnOn.apply(server);

console.log(result);
The Dell PowerEdge T30 is On 

在这个例子中,server 对象借用 computer 对象的 turnOn() 方法。同样,你可以在 server 对象调用 computer 对象的 turnOff() 方法。

let result = computer.turnOff.apply(server);
console.log(result);
The Dell PowerEdge T30 is Off

使用 apply() 方法将一个数组追加到另一个数组

apply() 方法允许您将数组的元素追加到另一个数组:

let arr = [1, 2, 3];
let numbers = [4, 5, 6];

arr.push.apply(arr, numbers);

console.log(arr); 

在此示例中,apply() 方法修改原始数组 arr。值得一提的是,Array.prototype.concat() 方法也有同样的效果,只是它返回新数组而不是修改原始数组。

  • apply() 方法调用函数使用指定的 this 值和一个类数组对象的参数。
  • apply() 方法与 call() 方法类似,只是 apply()  接受的参数是数组而不是单个参数

微信公众号

支付宝打赏

myfreax 淘宝打赏

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK