javascript distinguish apply and call the

  • Welcome to the front end of the exchange group to acquire video data and front-end learning materials: 749 539 640

The difference between the call and apply

ECMAScript specification for all functions are defined call with two methods apply, they are widely used, their role is exactly the same, but there are differences in the form of parameter passing it.

apply( )

two arguments apply method: as a function of the object context, a further parameter is an array as a function thereof.

var obj = {
    name : 'linxin'
}

function func(firstName, lastName){
    console.log(firstName + ' ' + this.name + ' ' + lastName);
}

func.apply(obj, ['A', 'B']);    // A linxin B

Can be seen, the object obj as a function of context, this refers to the function func in the object obj. Parameters A and B is on the list of elements in the array afferent function func, func corresponding parameters.

call( )

The method call is the first parameter as a function of the object context, it is passed back a list of parameters, instead of a single array.

var obj = {
    name: 'linxin'
}

function func(firstName, lastName) {
    console.log(firstName + ' ' + this.name + ' ' + lastName);
}

func.call(obj, 'C', 'D');       // C linxin D

We can see the difference apply contrast, C and D as a separate parameter to the function func, rather than into the array.

For when to use what method, in fact, do not tangle. If your parameters already exist in an array, then naturally use apply, if the argument is nothing more scattered association between each other, use call.

apply and call usage

1. Change this point

var obj = {
    name: 'linxin'
}

function func() {
    console.log(this.name);
}

func.call(obj);       // linxin

We know that the first argument of the method call as a function of the object context, where the obj passed as a parameter func, this time inside this function will point to the object obj. Here is the equivalent in function func

function func() {
    console.log(obj.name);
}

2. borrow another object's methods

Look at the example

var Person1  = function () {
    this.name = 'linxin';
}
var Person2 = function () {
    this.getname = function () {
        console.log(this.name);
    }
    Person1.call(this);
}
var person = new Person2();
person.getname();       // linxin

From the above we can see, Person2 instantiated objects person got out of the name by Person1 getname method. Because in Person2, the role of Person1.call (this) is to use Person1 objects instead of this object, Person2 have all the attributes and methods of Person1, which is equivalent Person2 inherits the properties and methods of Person1.

3. Call function

apply, call methods all functions executed immediately, so they may be used to invoke the function.

function func() {
    console.log('linxin');
}
func.call();            // linxin

The difference between the call and bind

Extension method called bind in EcmaScript5, it is not compatible with low version of IE. It is very similar to the call receiving part has two parameters, the first parameter is a function of the object as a context, the second part is a list of parameters that can accept a plurality of parameters.
The difference between them is the following two points.

The return value is a function of hair 1.bind

var obj = {
    name: 'linxin'
}

function func() {
    console.log(this.name);
}

var func1 = func.bind(obj);
func1();                        // linxin

bind method is not performed immediately, but the function returns after a context change this. The original function func of this has not been changed, still points to the global object window.

2. Use parameter

function func(a, b, c) {
    console.log(a, b, c);
}
var func1 = func.bind(null,'linxin');

func('A', 'B', 'C');            // A B C
func1('A', 'B', 'C');           // linxin A B
func1('B', 'C');                // linxin B C
func.call(null, 'linxin');      // linxin undefined undefined

is to call the second and subsequent arguments as arguments func pass in the method, the argument is actually func1 method then further back on the basis of the parameters in the bind.

In the low version of the browser does not bind method, we can also implement one yourself.

if (!Function.prototype.bind) {
        Function.prototype.bind = function () {
            var self = this,                        // 保存原函数
                context = [].shift.call(arguments), // 保存需要绑定的this上下文
                args = [].slice.call(arguments);    // 剩余的参数转为数组
            return function () {                    // 返回一个新函数
                self.apply(context,[].concat.call(args, [].slice.call(arguments)));
            }
        }
    }

Some use

  • ES6 inside the call to mass participation but also with deconstruction
const f = function (a, b, c) {
    console.log(a, b, c)
}
const arr = [1, 2, 3]
f.call(null, ...arr)
  • Seeking a maximum array using Math.max function, but this function is not supported by the reference arrays, only a plurality of parameters passed one by one, separated by commas.
let max = Math.max(1, 4, 8, 9, 0)//es5
let max = Math.max(...[1, 4, 8, 9, 0])//es6
//使用apply
let arr = [1, 4, 8, 9, 0];
let max = Math.max.apply(null, arr);

Description link

Guess you like

Origin www.cnblogs.com/wangzhichao/p/12160330.html
Recommended