Optional. A sequence of method parameters will be passed.
Explanation The
call method can be used to call a method instead of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj.
If the thisObj parameter is not provided, the Global object is used as thisObj.
To put it simply, the function of these two functions is actually to change the internal pointer of the object, that is, to change the content pointed to by this of the object. This is sometimes useful in object-oriented js programming. Let's take apply as an example to talk about the important role of these two functions in js. For example:
Copy code
The code is as follows:
function Person(name,age){ //Define a class
this.name=name; //Name
this. age=age; //Age
this.sayhello=function(){alert(this.name)};
}
function Print(){ //Display class attributes
this.funcName ="Print";
this.show=function(){
var msg=[];
for(var key in this){
if(typeof(this[key])!= "function"){
g.join(" "));
};
}
function Student(name,age,grade,school){ //Student class
Person.apply(this,arguments);//Superior to call Place
Print.apply(this,arguments);
this.grade=grade; //Grade
this.school=school; //School
}
var p1=new Person( "Bu Kaihua",80);
p1.sayhello();
var s1=new Student("Bai Yunfei",40,9,"Yuelu Academy");
s1.show();
s1.sayhello();
alert(s1.funcName);
In addition, Function.apply() plays a prominent role in improving program performance:
Let’s start with the Math.max() function. Math.max can be followed by any number of parameters, and finally returns the maximum value among all parameters.
For example
Copy code
The code is as follows:
alert(Math.max(5,8)); //8
alert(Math.max(5,7,9, 3,1,6)); //9
//But in many cases, we need to find the largest element in the array.
var arr=[5,7,9,1];
//alert(Math.max(arr)); // This is not possible. NaN
//Write like this
function getMax(arr){
var arrLen=arr.length;
for(var i=0,ret=arr[0];i< arrLen;i ){
ret=Math.max(ret,arr[i]);
alert(getMax(arr));
alert(arr); //9
//Switch to apply, you can write like this
function getMax2(arr){
return Math.max.apply(null,arr);
}
alert(getMax2(arr)); //9
//The two pieces of code achieve the same purpose, but getMax2 is elegant, efficient and much more concise.
//Another example is the push method of an array.
var arr1=[1,3,4];
var arr2=[3,4,5];
//If we want to expand arr2, then append to arr1 one by one, and finally Let arr1=[1,3,4,3,4,5]
//arr1.push(arr2) obviously does not work. Because doing this will get [1,3,4,[3,4,5]]
//We can only use a loop to push one by one (of course you can also use arr1.concat(arr2) , but the concat method does not change arr1 itself)
var arrLen=arr2.length;
for(var i=0;i arr1.push(arr2[i ]);
}
//Since Apply, things have become so simple
Array.prototype.push.apply(arr1,arr2); //Now arr1 is Desired results