Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

js apply和call的区别

作者:金钱打造势力狗。   发布日期:2025-05-03   浏览:76

// 示例代码:使用 call 和 apply 方法

function greet(name, age) {
  console.log(`Hello, my name is ${name} and I am ${age} years old. This function was called in the context of ${this}.`);
}

const person = { name: 'Alice', age: 30 };

// 使用 call 方法
greet.call(person, 'Bob', 25); 
// 输出: Hello, my name is Bob and I am 25 years old. This function was called in the context of [object Object]

// 使用 apply 方法
greet.apply(person, ['Charlie', 40]); 
// 输出: Hello, my name is Charlie and I am 40 years old. This function was called in the context of [object Object]

// 解释说明:
// call 和 apply 都可以改变函数的 this 指向,并立即调用函数。
// 主要区别在于传递参数的方式:
// - call 方法接受的是参数列表,直接将参数依次传入。
// - apply 方法接受的是一个参数数组,将数组作为参数传入。

上一篇:js 深拷贝对象

下一篇:js alter

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 获取今天年月日

js jsonp

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站