如何在JavaScript中使用apply(?),call(?)和bind(➰)方法

by Ashay Mandwarya ?️??

由Ashay Mandwarya提供吗?

如何在JavaScript中使用apply(?),call(?)和bind(➰)方法 (How to use the apply(?), call(?), and bind(➰) methods in JavaScript)

In this article, we’ll talk about the apply, call, and bind methods of the function prototype chain. They are some of the most important and often-used concepts in JavaScript and are very closely related to the this keyword.

在本文中,我们将讨论函数原型链的apply,call和bind方法。 它们是JavaScript中一些最重要且最常用的概念,并且与this关键字密切相关。

So, to get a grasp of the information in this article, first you have to be familiar with the concept and use of the this keyword. If you are already familiar with it then you can proceed — else, you can refer this article here and then come back here.

因此,要掌握本文中的信息,首先您必须熟悉this关键字的概念和用法。 如果您已经熟悉它,则可以继续进行;否则,您可以在这里参考本文,然后再回到这里。

To learn about apply|call|bind we need to know about functions in JavaScript too, assuming you are familiar with this.

要了解申请|电话|绑定 ,我们需要了解在JavaScript功能也一样,假设你是熟悉

功能 (Functions)

The Function constructor creates a new Function object. Calling the constructor directly can create functions dynamically, which can be executed in the global scope.

Function构造函数创建一个新的Function对象。 直接调用构造函数可以动态创建函数,这些函数可以在全局范围内执行。

As functions are objects in JavaScript, their invocation is controlled by the apply, call, and bind methods.

由于函数是JavaScript中的对象,因此它们的调用由apply,call和bind方法控制。

To check if a function is a Function object, we can use the code in the following snippet, which returns true.

要检查一个函数是否为Function对象,我们可以使用以下代码段中的代码,该代码返回true。

The global Function object has no methods or properties of its own. However, since it is a function itself, it does inherit some methods and properties through the prototype chain from Function.prototype. — MDN
全局Function对象没有自己的方法或属性。 但是,由于它本身是一个函数,因此它确实通过Function.prototype的原型链继承了一些方法和属性。 — MDN

The following are the methods in the function prototype chain:

以下是函数原型链中的方法:

  • Function.prototype.apply()

    Function.prototype.apply()

  • Function.prototype.bind()

    Function.prototype.bind()

  • Function.prototype.call()

    Function.prototype.call()

  • Function.prototype.isGenerator()

    Function.prototype.isGenerator()
  • Function.prototype.toSource()

    Function.prototype.toSource()
  • Object.prototype.toSource

    Object.prototype.toSource
  • Function.prototype.toString()

    Function.prototype.toString()
  • Object.prototype.toString

    Object.prototype.toString

We are concerned with the first three, so let’s begin.

我们关心的是前三个,所以让我们开始吧。

申请? (Apply ?)

The apply() method is an important method of the function prototype and is used to call other functions with a provided this keyword value and arguments provided in the form of array or an array like object.

apply()方法是函数原型的重要方法,用于通过提供关键字值和以数组或类似对象的数组形式提供的参数来调用其他函数。

Array-like objects may refer to NodeList or the arguments object inside a function.

类似数组的对象可以引用NodeList或函数内部的arguments对象。

This means that we can call any function and explicitly specify what this should reference in the calling function.

这意味着,我们可以调用任何功能,并明确指定哪些应在调用函数引用。

句法 (Syntax)
返回 (Return)

It returns the result of the function which is invoked by this.

它返回由此调用的函数的结果

描述 (Description)

The apply method is used for allowing a function/object belonging to an object x to be called and assigned to an object y.

apply方法用于允许调用属于对象x的功能/对象并将其分配给对象y。

例子 (Examples)
1。 (1.)

As seen in the given snippet, we see that when we push an array inside another, the whole array is treated as one element and pushed inside the array variable.

从给定的片段中可以看出,当我们将数组推入另一个数组时,整个数组将被视为一个元素并推入数组变量内部。

But what if we want the elements to be pushed individually instead as an array? Sure there are literally n number of ways to do so, but as we are learning apply, let’s use it:

但是,如果我们希望将元素作为数组分别推送,该怎么办? 当然,确实有n种方法可以使用,但是在学习应用的过程中,请使用它:

In the given example we can see the use of apply in joining two given arrays. The arguments array is the elements array and the this argument points to the array variable. The elements of the elements array are pushed to the Object(array) to which the this is pointing. We get the result as the second array’s individual elements pushed to the array to which the this is pointed.

在给定的示例中,我们可以看到apply在连接两个给定数组中的使用。 arguments数组是elements数组, this参数指向array变量。 elements数组的元素被推送到this所在的Object( array ) 指向 当第二个数组的各个元素被推到this指向的数组时,我们得到结果。

2。 (2.)

The max function in JS is used to find the element with the maximum value from a given pool of elements. But as we can see from the snippet, if the values are in the form of an array, we get the result as NaN. Surely we are talking about JavaScript so again, there are n number of ways doing this, but let’s use apply.

JS中的max函数用于从给定的元素池中找到具有最大值的元素。 但是,正如我们从代码段中看到的那样,如果值采用数组形式,则结果将以NaN表示。 当然,我们在再次谈论JavaScript,因此有无数种方法可以做到这一点,但让我们使用apply。

Now when we use apply and use the Math.max() function, we get the result. As we know, the apply will take all the values inside the array as individual arguments and then the max function will be applied to them. This will give us the maximum value in the array.

现在,当我们使用apply和Math.max()函数时,我们得到了结果。 众所周知,apply将数组中的所有值作为单独的参数,然后将max函数应用于它们。 这将为我们提供数组中的最大值。

An interesting thing to point out here is that in place of this we have used null. As the argument provided is the number array, even if this is introduced it will point to the same array and we will get the same result. Therefore, in such cases, we can use null in place of this. This shows us that the this argument in the apply function is an optional argument.

这里要指出的一个有趣的事情是,我们使用null代替了 。 由于提供的参数是数字数组,即使这个介绍会指向同一个数组,我们会得到相同的结果。 因此,在这种情况下,我们可以使用null代替它。 这向我们显示了apply函数中的this参数是一个可选参数。

呼叫 (Call)

The call() method is used to call a function with a given this and arguments provided to it individually.

call()方法用于调用具有给定的this和单独提供给它的参数的函数。

This means that we can call any function, explicitly specifying the reference that this should reference in the calling function.

这意味着,我们可以调用任何功能,明确指定, 应在调用函数引用参考。

This is very similar to apply, the only difference being that apply takes arguments in the form of an array or array-like objects, and here the arguments are provided individually.

这与apply非常相似唯一的不同是apply适用于采用数组或类似数组的对象形式的参数,这里的参数是单独提供的。

句法 (Syntax)
返回 (Return)

The result of calling the function with the specified this value and arguments.

使用指定的this值和参数调用函数的结果。

描述 (Description)

The call method is used for allowing a function/object belonging to an object x to be called and assigned to an object y.

调用方法用于允许调用属于对象x的功能/对象并将其分配给对象y。

例子 (Examples)
1。 (1.)

This is an example of constructor chaining. As we can see, in every function the constructor of the Product is called, and using call the properties of the Product object are chained with the Pizza and Toy objects, respectively.

这是构造函数链接的示例。 如我们所见,在每个函数中,都会调用Product的构造函数,并使用call分别将Product对象的属性与Pizza和Toy对象链接在一起。

When new instances are created of the Pizza and Toy objects, parameters are provided as name, price and category. Category is applied in the definition only, but the name and price are applied using the chained constructor of the Product object, as they are defined and applied in the Product object. With a little more tweaking we can achieve inheritance.

当创建Pizza和Toy对象的新实例时,将以名称,价格和类别提供参数。 类别仅在定义中应用,但是名称和价格是通过使用Product对象的链接构造函数来应用的,因为它们是在Product对象中定义和应用的。 稍加调整,就可以实现继承。

2。 (2.)

In the snippet above, we defined a function called sleep. It consists of an array reply which consists of elements which address properties using the this keyword. They are defined in a separate object outside the function.

在上面的代码段中,我们定义了一个名为sleep的函数。 它由一个数组回复组成,该数组回复包含使用this关键字处理属性的元素。 它们在函数外部的单独对象中定义。

The function sleep is called with the object obj as an argument. As we can see, the properties of the obj are set in the this.animal and this.sleepDuration, respectively, and we get the full sentence as output.

使用对象obj作为参数调用功能sleep。 如我们所见, obj的属性分别在this.animalthis.sleepDuration中设置,我们将完整的句子作为输出。

绑定➰ (Bind➰)

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called. — MDN

bind()方法创建一个新函数,该函数在被调用时将其this关键字设置为提供的值,并在调用新函数时提供给定的参数序列。 — MDN

句法 (Syntax)
返回 (Return)

Bind returns a copy of the function with the supplied this and the arguments.

Bind返回带有提供的this和参数的函数副本。

描述 (Description)

The bind function is much like the call function, with the main difference being that bind returns a new function whereas call does not.

bind函数非常类似于call函数,主要区别在于bind返回一个新函数,而call不返回。

According to ECMAScript 5 specifications, the function returned by bind is a special type of exotic function object (as they call it) called the Bound function (BF). The BF wraps the original function object. Calling a BF runs the wrapped function in it.

根据ECMAScript 5规范, bind返回的函数是一种特殊类型的外来函数对象(如他们所称),称为绑定函数 (BF) 。 BF包装原始函数对象。 调用BF将在其中运行包装的函数。

例子 (Examples)
1。 (1.)

In the above snippet, we have defined a variable x and an object called module. It also contains a property called x and another property whose corresponding value is a function which returns the value of x.

在上面的代码段中,我们定义了一个变量x和一个名为module的对象。 它还包含一个名为x的属性和另一个属性,该属性的相应值是一个返回x值的函数

When the function getX is called it returns the values of x which is defined inside the object and not the x in the global scope.

的getX被调用它的函数返回该对象,而不是在全球范围内的X内限定x的值。

Another variable is declared in the global scope which calls the getX function from the module object. But as the variable is in the global scope, the this in the getX points to the global x and hence 9 is returned.

在全局范围内声明了另一个变量,该变量从模块对象调用getX函数。 但是由于变量在全局范围内,因此getX中this指向全局x ,因此返回9。

Another variable is defined which calls the previous function but this time binds the said function with the module object. This binding returns the value of x inside the object. Due to the binding, the this in the function points to the value of x in the object and not the global x. Hence we get 81 as the output

定义了另一个变量,该变量调用先前的函数,但是这次将所述函数与模块对象绑定。 该绑定返回对象内部的x值。 由于绑定,函数中的this指向对象中x的值,而不是全局x 。 因此我们得到81作为输出

结论 (Conclusion)

Now that we have learned the basics about the methods, you might still be a little bit confused about why there are 3 different functions doing almost the same thing. To clarify this concept, you have to practice with different situations and scenarios so you can learn more thoroughly where and how they can be used. They will for sure make your code cleaner and more powerful.

既然我们已经了解了这些方法的基础知识,那么对于为什么有3个不同的函数几乎可以完成相同的事情,您可能仍然有些困惑。 为了阐明这个概念,您必须在不同的情况和场景下进行练习,以便可以更全面地学习在何处以及如何使用它们。 它们肯定会使您的代码更干净,更强大。

If you liked this article, please clap? and follow? for more.

如果您喜欢这篇文章,请鼓掌? 并跟随? 更多。

翻译自: https://www.freecodecamp.org/news/how-to-use-the-apply-call-and-bind-methods-in-javascript-80a8e6096a90/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值