call/apply和 bind

发布时间 2023-09-13 15:22:41作者: 大海&

call

接受多个参数,第一个参数表示 this 的指向,后面的多个参数都是传参

function person(name, age) {
	console.log(`my name is ${name} age is ${age}`);
}	
person.call(this, '大海', 18);

apply

接受两个参数,第一个参数表示 this 的指向,第二个参数为数组

function person(name, age) {
	console.log(`my name is ${name} age is ${age}`);
}
person.apply(this, ['大海', 18]);

bind

和 call 接受的参数一致,只是 bind会返回一个新的函数

function person(name, age) {
	console.log(`my name is ${name} age is ${age}`);
}	

let ocean = person.bind(this, '大海', 18);
ocean();