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

js call apply bind区别

作者:噬血啸月   发布日期:2025-07-24   浏览:40

// 使用 call 方法
function greet(name, age) {
  console.log(`Hello, my name is ${name} and I am ${age} years old. This function was called by ${this.name}.`);
}

const obj = { name: 'Alice' };

greet.call(obj, 'Bob', 30); 
// 输出: Hello, my name is Bob and I am 30 years old. This function was called by Alice.

// 使用 apply 方法
function greetWithApply(name, age) {
  console.log(`Hello, my name is ${name} and I am ${age} years old. This function was called by ${this.name}.`);
}

greetWithApply.apply(obj, ['Charlie', 25]);
// 输出: Hello, my name is Charlie and I am 25 years old. This function was called by Alice.

// 使用 bind 方法
function greetWithBind(name, age) {
  console.log(`Hello, my name is ${name} and I am ${age} years old. This function was called by ${this.name}.`);
}

const boundGreet = greetWithBind.bind(obj, 'David', 35);
boundGreet(); 
// 输出: Hello, my name is David and I am 35 years old. This function was called by Alice.

解释说明:

  • call 方法:立即调用函数,并将指定的对象作为 this 上下文传递给函数,同时可以传递参数列表。
  • apply 方法:与 call 类似,但参数是以数组的形式传递。
  • bind 方法:创建一个新的函数,并将指定的对象作为 this 上下文绑定到该新函数上。新函数可以在稍后的时间点被调用。

以上代码展示了如何使用 callapplybind 来改变函数的 this 上下文并传递参数。

上一篇:js gzip

下一篇:js apply call

大家都在看

js 数组对象排序

js 数组删掉第一个值

js fill

js json数组

js 数组复制

js 复制数组

js 数组拷贝

js 对象转数组

js 深拷贝数组

js 点击空白区域触发事件

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

Laravel 中文站