Basic usage of both
The call() method is similar to apply() except that call() takes a list of parameters, while apply() takes an array of parameters.
call
The call() method calls a function with a specified this value and one or more arguments given separately.
The call of the grammar
fun.call(thisArg, arg1, arg2, ...)
Copy the code
parameter
-
thisArg
The this value specified when fun is run. If (thisArg = = undefined | null) this = window, if(thisArg == number|boolean|string) this == new Number()|new Boolean()| new String()
-
arg1
,arg2
,...
Specifies the argument list.
The application of the call
Use the call method to call the parent constructor for inheritance
In this example, the child constructor Sun() implements inheritance by calling the call method of the parent constructor Father(), at which point the Sun() function has the attributes in Father().
function Father(name,age){
this.name = name;
this.age = age;
this.book=['Data structure'.'Computer Network'.'algorithms']
console.log('1. Execute to Father-- name: '+this.name+'; Age: '+this.age+'Books:'+this.book);
}
function Sun(name,age){
Father.call(this,name,age);
this.subject = 'Software Major';
console.log('2. Execute to Sun-- Professional: '+this.subject);
}
var sun = new Sun('gxm'.'20');
sun.book.push('javaScript');
console.log('3. Change sun.book: '+sun.book);
var sun2 = new Sun('xz'.'22');
Copy the code
The results
1. Execute to Father-- name: GXM; Age: 20 Books: Data Structures, Computer Networks, Algorithms 2. Performed to Sun-- Major: Software major 3. Change sun.book: Data Structures, Computer Networking, Algorithms,javaScript 1. Execute to Father-- name: xz; Age: 22 Books: Data Structures, Computer Networks, Algorithms 2. Performed to Sun-- Major: Software major 4. See SUN2.book: Data Structures, Computer Networks, AlgorithmsCopy the code
As you can see from the result, the new instance changes the inherited properties, not the original function.
Call the function using the call method and specify this for the context
function play() {
var reply = [this.player, '打', this.playName,'the',this.playTimes].join(' ');
console.log(reply);
}
var obj = {
player: 'gxm',playName: 'badminton', playTimes: '1 hour'}; play.call(obj); // GXM played badminton for an hourCopy the code
If you run the play() function directly, the result will just be typing. Play.call (obj) assigns the play() function’s context from the global window to the obj object. So the result of running out became GXM playing badminton for 1 hour.
Consider several this in the following code:
function foo() {
return() = > {return() = > {return () => {
console.log('id:', this.id);
};
};
};
}
var f = foo.call({id: 1});
var t1 = f.call({id: 2})()(); // id: 1
var t2 = f().call({id: 3})(); // id: 1
var t3 = f()().call({id: 4}); // id: 1
Copy the code
In the code above, there is only one this, which is the this of function foo, so t1, T2, t3 all output the same result. Because all the inner functions are arrow functions and don’t have their own this, their this is actually the this of the outermost foo function.
The call method is used to call the function without specifying the first argument section
In the example below, we call the display method without passing its first argument. If the first argument is not passed, the value of this will be bound as a global object.
var sData = 'Wisen';
function display() {
console.log('sData value is %s ', this.sData);
}
display.call(); // sData value is Wisen
Copy the code
Note: In strict mode, the value of this will be undefined. See below.
'use strict';
var sData = 'Wisen';
function display() {
console.log('sData value is %s ', this.sData);
}
display.call(); // Cannot read the property of 'sData' of undefined
Copy the code
apply
The apply() method calls a function with a given this value and the arguments supplied as an array (or array-like object).
Apply the grammar
func.apply(thisArg, [argsArray])
parameter
-
thisArg
Optional. The this value used when the func function is run. Note that this may not be the actual value seen by the method: if the function is in non-strict mode, specifying null or undefined is automatically replaced with pointing to a global object, and the original value is wrapped.
-
argsArray
Optional. An array or array-like object whose array elements are passed as individual arguments to the func function. If the value of this parameter is null or undefined, no arguments need to be passed in. Array-like objects can be used starting with ECMAScript 5.
The application of the apply
Apply implementation inheritance
function superType() {
this.color = ['red'.'blue'.'yellow']}function subType() {/ / - inherited the superType - superType. Applay (this); //superType.call(this); } var instance1 = new subType(); instance1.color.push('green');
console.log('instance1.color:', instance1.color);
//instance1.color: (4) ["red"."blue"."yellow"."green"]
Copy the code
Use Apply to add an array to another array
We can append elements to an array using push. And, because push takes a variable number of arguments, we can also push multiple elements at once.
However, if we pass an array to push, it actually adds that array as a single element, not as a separate element, so we end up with an array within an array. What if that’s not what we want? In this case, concat does have the desired behavior, but it doesn’t actually append to an existing array; instead, it creates and returns a new array.
But we want to attach to our existing array…… And now? Write a loop? Of course not?
Apply is here to help!
var array = ['a'.'b']; var elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); / / /"a"."b", 0, 1, 2]
Copy the code
The same
Call and apply work in the same way: call a function with a specified this value and one or more arguments given separately.