Home > Web Front-end > JS Tutorial > Detailed introduction of functions apply() and call()

Detailed introduction of functions apply() and call()

不言
Release: 2019-03-30 09:15:39
forward
3089 people have browsed it

This article brings you a detailed introduction to the functions apply() and call(). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Introduction to apply and call in functions

When it comes to apply and call, we must first talk about their origins with functions

Javascript functions are both objects

It is no different from other javascript objects. And each function contains two non-inherited methods apply() and call(), both of which can indirectly call the function

For example:

function f() {
    console.log(1);
}
f.call(); //1
f.apply(); //1
Copy after login

And these two methods Each method allows the display of the this value after the specified function call.

Regarding the value of this, since the value of this is confirmed when entering the execution context stage, the value of this is confusing. But we can explicitly specify the required this value when the function is called through apply() and call().

So what are the apply and call methods used for?

Any function can be assigned this value when called and called as a method of the object pointed to by this.

That means any function can be called by any object. This is the ultimate goal of the apply and call methods.

Let us take a usage example to understand

function Animal() {};
Animal.prototype = {
    constructor: Animal,
    other: function() {
        console.log('这是一只' + this.name);
    }
}
var animal = new Animal();
//定义一个对象
var dog = {
    name: '狗'
};

//我的dog对象想使用Animal函数的other方法怎么办,使用call或apply
animal.other.call(dog);
animal.other.apply(dog);
Copy after login

In the above, we use animal.other (think about what it is, yes, it is essentially a function) as the dog object method call. Next, we use some practical ones.

//设置一个类数组对象
var arrLike = {
    0: '我是apply',
    1: '我是call',
    length: 2
}

//将Arrar的slice函数的this显式指向arrLike,并将0作为参数传入slice函数
var newArr = Array.prototype.slice.call(arrLike, 0);
//等价于 
arrLike.slice(0);
console.log(newArr);
Copy after login

For apply() and cal(), all the first arguments passed to them will become the value of this, Even if the passed arguments Is the original value , null, undefined. And if the first actual parameter passed in is undefined or null, it will be replaced by the global object in ES3 and non-strict mode, and other original values ​​will be replaced by the corresponding wrapper object.

In layman's terms, Js doesn't care what the first parameter of apply/call is. The function will still be called, but whether the call will report an error is another matter.

var str = '我是一个函数';
//将字符串传入,但是String对象无法调用slice属性 报错
Array.prototype.pop.call(str);
Copy after login

In order to remember these two methods deeply and when to use these two methods, list some common usages

First of all, for now, the performance difference between these two methods Almost ignored, so how to use them?

apply() method is suitable for passing in the second parameter in order and the parameters are uncertain. Use the apply method, such as the arguments of a function. This array-like object is very suitable for passing as a parameter.

function A(a, b, c) {
    console.log(a, b, c);
}

var fn = (function(func, b, c) {
    var args = arguments;
    return () => {
        func.apply(null, args);
    }
}(A, 66, 99));

fn();
Copy after login

Another example is to append elements to the array

var arr1 = [1, 2, 3];
var arr2 = [66, 99, 131];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1);
Copy after login

Similarly pass the arr2 array as a parameter.

For unordered parameters that are not related to each other, use call()

to obtain the maximum and minimum values ​​of the array

var arr = [0, 1, 2, 3, 4];

//获取最大数
var max1 = Math.max.apply(Math, arr),
    max2 = Math.max.call(Math, 0, 1, 2, 3, 4),

    //获取最小数
    min1 = Math.min.apply(Math, arr),
    min2 = Math.min.call(Math, 0, 1, 2, 3, 4);
console.log(max1, max2, min1, min2);
Copy after login

arr itself does not have a Math method, but we can use call or apply to use its method

Determine the specific type of the object

//验证对象的具体类型
var arr = [];
var type = Object.prototype.toString.call(arr);
console.log(type);// [object Array]
Copy after login

Obtained when using typeof The results are all Object, and it is impossible to determine which type they are. So you can use Object.prototype.toString.call() to get the specific type. Of course, the premise is that the toSting() method has not been overridden

Convert the array-like object into a real array, usually we use Array.prototype.slice.call() to convert

var arrLike = {
    length: 3,
    0: '值1',
    1: '值2',
    2: '值3'
}
var newArr = [].__proto__.slice.call(arrLike);
var type = Object.prototype.toString.call(newArr);
console.log(newArr, type); //[ '值1', '值2', '值3' ] '[object Array]'
Copy after login

Of course, splice,concat can also convert array-like objects into arrays.

Here is a popularization of array-like objects.
Access elements through indexes and have the length attribute
In other words, two conditions need to be met, 1. Use serial numbers to define attributes, 2. Have the length attribute, the attribute value is the number of elements
When using serial numbers When defining attributes, it is recommended to define attributes in order starting from 0. Otherwise, the array element will be empty

var arrLike = {
    length: 3,
    0: '值1',
    1: '值2',
    3: '值3'
}
var newArr = [].__proto__.slice.call(arrLike);
var type = Object.prototype.toString.call(newArr);
console.log(newArr, type); //[ '值1', '值2', empty] [object Array]
Copy after login

This article has ended here. For more exciting content, you can pay attention to the JavaScript Video Tutorial column on the PHP Chinese website!

The above is the detailed content of Detailed introduction of functions apply() and call(). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template