如何在 JavaScript 中使用call、apply 和 bind函数(上)

487 阅读3分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第23天,点击查看活动详情

如何在 JavaScript 中使用调用函数

call是一个函数,用于更改this函数内部的值并使用提供的参数执行它。

这是call函数的语法:


func.call(thisObj, args1, args2, ...)

在哪里,

  • func是一个需要用不同的this对象调用的函数
  • thisObj是一个对象或一个值,需要用this函数内部的关键字替换func
  • args1, args2是传递给带有更改this对象的调用函数的参数。

请注意,如果你调用一个没有任何thisObj参数的函数,那么 JavaScript 会将此属性视为一个全局对象。

现在我们已经了解了call函数是什么的一些背景信息,让我们从通过一些示例更详细地了解它开始。

如何在 JS 中调用具有不同上下文的函数

考虑下面的例子。它由 3 个类组成 - CarBrand1Brand2

function Car(type, fuelType){
	this.type = type;
	this.fuelType = fuelType;
}

function setBrand(brand){
	Car.call(this, "convertible", "petrol");
	this.brand = brand;
	console.log(`Car details = `, this);
}

function definePrice(price){
	Car.call(this, "convertible", "diesel");
	this.price = price;
	console.log(`Car details = `, this);
}

const newBrand = new setBrand('Brand1');
const newCarPrice = new definePrice(100000);

如果你仔细看,你会发现我们使用call函数调用了Car两次函数。首先,在函数中setBrand,然后在definePrice函数中。

在这两个函数中,我们使用表示各自函数本身的对象来调用Car函数。this例如,在内部setBrand,我们使用属于其上下文Car的对象调用函数。this情况与definePrice.

如何在 JS 中调用不带参数的函数

考虑下面的例子:

const newEntity = (obj) => console.log(obj);

function mountEntity(){
	this.entity = newEntity;
	console.log(`Entity ${this.entity} is mounted on ${this}`);
}

mountEntity.call();

在这个例子中,我们调用了mountEntity没有thisObj参数的函数。在这种情况下,JavaScript 指的是全局对象。

如何在 JavaScript 中使用 Apply 函数

Apply函数与函数非常相似Callcall和之间的唯一区别apply是参数传递方式的不同。

apply, arguments 中,你可以将参数作为数组文字或新数组对象传递。

这是apply函数的语法:

func.apply(thisObj, argumentsArray);

在哪里,

  • func是一个需要用不同的this对象调用的函数
  • thisObj是一个对象或一个值,需要用this函数内部的关键字替换func
  • argumentsArray可以是参数数组、数组对象或arguments关键字本身。

正如你在上面看到的,该apply函数具有不同类型的语法。

第一种语法很简单。你可以传入一个参数数组,如下所示:

func.apply(thisObj, [args1, args2, ...]);

第二种语法是我们可以将新数组对象传递给它的地方:

func.apply(thisObj, new Array(args1, args2));

第三种语法是我们可以传入 arguments 关键字的地方:

func.apply(thisObj, arguments); 

arguments是函数内部可用的特殊对象。它包含传递给函数的参数值。你可以将此关键字与apply函数一起使用以获取任意数量的任意参数。

最好的部分apply是我们不需要关心传递给调用函数的参数数量。由于其动态性和多功能性,你可以在复杂的情况下使用它。

让我们看一下与上面相同的示例,但这次我们将使用该apply函数。

function Car(type, fuelType){
	this.type = type;
	this.fuelType = fuelType;
}

function setBrand(brand){
	Car.apply(this, ["convertible", "petrol"]); //Syntax with array literal
	this.brand = brand;
	console.log(`Car details = `, this);
}

function definePrice(price){
	Car.apply(this, new Array("convertible", "diesel")); //Syntax with array object construction
	this.price = price;
	console.log(`Car details = `, this);
}

const newBrand = new setBrand('Brand1');
const newCarPrice = new definePrice(100000);

这是一个示例,展示了如何使用arguments关键字:

function addUp(){
		//Using arguments to capture the arbitrary number of inputs
    const args = Array.from(arguments); 
    this.x = args.reduce((prev, curr) => prev + curr, 0);
    console.log("this.x = ", this.x);
}

function driverFunc(){
    const obj = {
        inps: [1,2,3,4,5,6]
    }
    addUp.apply(obj, obj.inps);
}

driverFunc();