Detailed resolution of the use of the apply method in js

  • 2020-03-26 23:07:36
  • OfStack

1, Object inheritance, the general practice is to copy: object.extend
Prototype.js is implemented as follows:


Object.extend = function(destination, source) { 
    for (property in source) { 
        destination[property] = source[property]; 
    } 
    return destination; 
}

Function. Apply (Function. Call is also ok)

The apply method can hijack another object's methods and inherit another object's properties

The Function. Apply (obj,args) method can take two arguments

Obj: This object will replace this object in the Function class

The args. This is the array, which is passed to Function as an argument. The arguments)

The apply sample code is as follows:


<script> 
function Person(name,age){   //Define a class, human & NBSP;
    this.name=name;     //Name  
    this.age=age;       // age  
    this.sayhello=function(){alert("hello")};
} 
function Print(){            //Displays the properties of the class
    this.funcName="Print"; 
    this.show=function(){      
        var msg=[];
        for(var key in this){ 
            if(typeof(this[key])!="function"){
                msg.push([key,":",this[key]].join(""));
            }
        } 
        alert(msg.join(" "));
    };
} 
function Student(name,age,grade,school){    //Students in class
    Person.apply(this,arguments);
    Print.apply(this,arguments);
    this.grade=grade;                // grade  
    this.school=school;                 // The school  
} 
var p1=new Person("jake",10);
p1.sayhello();
var s1=new Student("tom",13,6," Tsinghua primary school ");
s1.show();
s1.sayhello();
alert(s1.funcName);
</script>

The student class doesn't have any methods, but after person. apply(this,arguments),

He has the sayhello method of the Person class and all its properties.

The show() method is automatically obtained after print.apply (this,arguments)

2. Use the parameter grouping of Apply to improve

Function. Apply () tips for improving program performance

Let's start with the math.max () function, which can be followed by any argument and returns the maximum of all arguments.

Such as
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 the case. You have to write it 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]);       
    }
    return ret;
}

This is cumbersome and inefficient. What about apply? Look at the code:

function getMax2(arr){
    return Math.max.apply(null,arr);
}

Both pieces of code serve the same purpose, but getMax2 is elegant, efficient, and much simpler.

Or the push method of an array.
Var arr1 = [1 4];
Var arr2 = (three, four, five);

So if we were to expand arr2, and then append it one by one to arr1, then arr1 would be equal to [1,3,4,3,4,5].
Arr1. Push (arr2) obviously doesn't work. Because you get [1,3,4,[3,4,5]]

We can only use one loop to push one by one (of course, we can also use arr1. Concat (arr2), but the concat method does not change arr1 itself).


var arrLen=arr2.length
for(var i=0;i<arrLen;i++){
    arr1.push(arr2[i]);
}

Since Apply, things have been so simple
Array. The prototype. Push. Apply (arr1, arr2)


Related articles: