In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Editor to share with you how Javascript uses. Call () and. Apply () to write better code. I hope you will learn something after reading this article. Let's discuss it together.
The prototype of the Javascript function object exposes two valuable methods, call () and apply ().
First of all, let's understand the role of each method.
.call () function
The call () function is used to call the function through the context of the this provided to it. It allows us to call a function by explicitly providing an object for the this event within a particular function.
To better understand why this approach exists, consider the following example:
Function sayHello () {console.log (`Hello, ${this.name} `);} sayHello (); / / Hello, undefined
As you can see, the interior of the this function refers to the global scope. In the above code, the sayHello function tries to find a variable named name globally. Since there is no such variable, it prints out undefined. If we define a name variable that is called globally, the function will work as expected, as shown below:
Const name = 'archeun';function sayHello () {console.log (`Hello, ${this.name}`);} sayHello (); / / Hello, archeun if we strictly use the pattern in the above code, it will actually throw a run-time error because this will be undefined.
The disadvantage here is that the sayHello function assumes the scope of the this variable, and we can't control it. This function behaves differently depending on the lexical scope in which we execute it. This is when the call () method comes in handy. As you know, it allows us to explicitly inject objects that we need for internal variables in the this function:
Consider the following example:
Const name = 'archeun';function sayHello () {console.log (`Hello, ${this.name} `);} sayHello (); / / Hello, archeunconst visitor = {name:' My lordship'} / * The first parameter of the call method is, * the object to be used for the `this` context inside the function. * So when the `sayHello` function encounters `this.name`, it now knows * to refer to the `name` key of the `visitor`object we passed * to the `call` method. * / sayHello.call (visitor); / / Hello, My lordhammer context * * Here we do not provide the `this`. * This is identical to calling sayHello (). * The function will assume the global scope for `this`. * / sayHello.call (); / / Hello, archeun
In addition to the context passed by this as the first argument to the method, call () also accepts the parameters of the called function. After the first argument, all other parameters that we pass to the call () method are passed as arguments to the called function.
Function sayHello (greetingPrefix) {console.log (`${greetingPrefix}, ${this.name}`);} const visitor = {name:'My lordholders'} / * * Here `Hello`Hello` will be passed as the argument to the * `greetingPrefix` parameter of the `sayHello` function * / sayHello.call (visitor, 'Hello'); / / Hello, My lordholders Universe * * Here `hody`will be passed as the argument to the * `greetingPrefix` parameter of the `sayHello` function * / sayHello.call (visitor,' Howdy'); / / Howdy, My lord! Use method 1. Reusable context-free functions
We can write a function and call it in different this contexts:
Function sayHello (greetingPrefix) {console.log (`${greetingPrefix}, ${this.name}`);} const member = {name: 'Well-known member'} const guest = {name:' Random guest'} / * `sayHello` function will refer to the `member`object * whenever it encouneters `this` * / sayHello.call (member, 'Hello'); / / Hello, Well-known member/** * `sayHello`function will refer to the `guest`object * whenever it encouneters `this` * / sayHello.call (guest,' Howdy') / / Howdy, Random guest
As you can see, if used properly, this can improve the reusability and maintainability of the code.
two。 Constructor chain
We can use the call () method to link the constructor of the object created by the function. When you use this function to create an object, the function can take another function as its constructor. As shown in the following example, both Dog and Fish call the Animal function to initialize their public properties, namely name and noOfLegs:
Function Animal (name, noOfLegs) {this.name = name; this.noOfLegs = noOfLegs;} function Dog (name, noOfLegs) {/ / Reuse Animal function as the Dog constructor Animal.call (this, name, noOfLegs); this.category = 'mammals';} function Fish (name, noOfLegs) {/ / Reuse Animal function as the Fish constructor Animal.call (this, name, noOfLegs); this.category =' fish';} const tiny = new Dog ('Tiny', 4) Const marcus = new Fish ('Marcus', 0); console.log (tiny); / / {name: "Tiny", noOfLegs: 4, category: "mammals"} console.log (marcus); / / {name: "Marcus", noOfLegs: 0, category: "fish"}
This is also a variant of code reuse. This pattern also enables us to write code close to OOP principles in other languages.
3. Use objects to call anonymous functions
Anonymous functions inherit the lexical scope that calls them. We can use the call () method to explicitly inject the this scope into the anonymous function. Consider the following example:
Const animals = [{type: 'Dog', name:' Tiny', sound: 'Bow wow'}, {type:' Duck', name: 'Marcus', sound:' Quack'}]; for (let I = 0; I
< animals.length; i++) { /** * This anonymous function now has access to each animal object * through `this`. */ (function (i) { this.makeSound = function () { console.log(`${this.name} says ${this.sound}!`); } this.makeSound(); }).call(animals[i], i);}// Tiny says Bow wow!// Marcus says Quack! 在这里,我们不必实现一个专门的函数来将makeSound方法附加到每个动物对象上。这使我们无法编写和命名一次性使用的实用程序函数。 这些是我们可以有效地使用call()方法使我们的代码干净、可重用和可维护的几种方法。 .apply()作用 apply()在功能方面几乎与call()方法相同。唯一的区别是它接受一个类似数组的对象作为它的第二个参数。 /** * After `this` context argument * `call` accepts a list of individual arguments. * Therefore, if `args` is an array, we can use the * `ES6` spread operator to pass individual elements * as the list of arguments */func.call(context, ...args);/** * After `this` context argument * `apply` accepts a single array-like object * as its second argument. */func.apply(context, args); 除了apply()如何处理被调用方参数外,该功能与call()方法相同。但是,由于这种差异,我们可以将其用于不同于call()的用例。 使用方法1. 连接(追加)数组 Array.prototype.push函数可用于将元素推送到数组的末尾。例如: const numbers = [1, 2, 3, 4];numbers.push('a', 'b', 'c'); // push elements on by oneconsole.log(numbers); // [1, 2, 3, 4, "a", "b", "c"] 如果你想将一个数组的所有元素推送到另一个数组,该怎么办?像下面这样: const numbers = [1, 2, 3, 4];const letters = ['a', 'b', 'c'];numbers.push(letters);console.log(numbers); // [1, 2, 3, 4, ["a", "b", "c"]] 这并不是我们想要的。它将整个字母数组作为单个元素附加到数字数组。我们本可以使用concat()方法,但它将创建数组的副本并返回它。我们也不需要。我们还可以在字母数组上循环并单独推送每个元素。但还有一种更优雅的方式: const numbers = [1, 2, 3, 4];const letters = ['a', 'b', 'c'];numbers.push.apply(numbers, letters);console.log(numbers); // [1, 2, 3, 4, "a", "b", "c"] 如果我们有特权使用ES6扩展运算符,我们可以通过这样做来实现这一点, const numbers = [1, 2, 3, 4];const letters = ['a', 'b', 'c'];numbers.push(...letters);console.log(numbers); // [1, 2, 3, 4, "a", "b", "c"]2.apply()与接受参数列表的内置函数一起使用 对于任何接受参数列表的函数,例如Math.max我们可以有效地使用 apply。考虑以下。 如果你想找出一组数字的最小值和最大值,下面是老派的做法: let min = +Infinity;let max = -Infinity;const numbers = [4, 5, 1, 2, 8, 3, 4, 6, 3];for (let i = 0; i < numbers.length; i++) { if (numbers[i] >Max) {max = numbers [I];} if (numbers [I] < min) {min = numbers [I];}} console.log (`Min: ${min}, Max: ${max} `); / / Min: 1, Max: 8
We can apply () to achieve the same effect in a more elegant way, as follows:
Const numbers = [4,5,1,2,8,3,4,6,3]; min = Math.min.apply (null, numbers); max = Math.max.apply (null, numbers); console.log (`Min: ${min}, Max: ${max} `); / / Min: 1, Max: 8
As in the previous case, if we can use the ES6 extension operator, we can achieve the same effect by doing the following:
Const numbers = [4, 5, 1, 2, 8, 3, 4, 6, 3]; min = Math.min (.minutes); max = Math.max (.minutes); console.log (`Min: ${min}, Max: ${max} `) / / Min: 1, Max: 8 after reading this article, I believe you have some understanding of "how Javascript writes better code using .call () and .apply ()". If you want to know more about it, welcome to follow the industry information channel. Thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.