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

js call apply bind

作者:昔日暖阳   发布日期:2026-08-02   浏览:63

// 使用 call 方法
function greet(greeting, punctuation) {
  console.log(greeting + ' ' + this.name + punctuation);
}

const person = { name: 'Alice' };

greet.call(person, 'Hello', '!');  // 输出: Hello Alice!

// 使用 apply 方法
function introduce(adjective1, adjective2) {
  console.log(`I am ${this.name}, I'm ${adjective1} and ${adjective2}.`);
}

introduce.apply(person, ['brave', 'smart']);  // 输出: I am Alice, I'm brave and smart.

// 使用 bind 方法
function farewell(goodbye) {
  console.log(goodbye + ', ' + this.name);
}

const sayGoodbye = farewell.bind(person, 'Goodbye');
sayGoodbye();  // 输出: Goodbye, Alice

解释说明:

  • call 方法:调用一个函数,并将函数内部的 this 指向指定的对象,同时可以传递参数。参数以逗号分隔的形式传入。
  • apply 方法:与 call 类似,但它接受一个参数数组(或类数组对象)来传递给函数。
  • bind 方法:创建一个新的函数,在调用时设置这个新函数的 this 值为提供的值,并且可以预设部分参数。返回的新函数可以在之后被调用。

上一篇:js 对象转map

下一篇:js switch 用法

大家都在看

js 数组打乱顺序

js 两个数组取交集

js 数组对象排序

js 对象数组排序

js 数组删掉第一个值

js fill

js fill方法

js 数组连接

js json数组

js 数组复制

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

Laravel 中文站