The usage of apply,call,bind

Keywords: Javascript Java

apply()

Function.prototype.apply() will call a method with arguments in the form of this and an array.
m

fun.apply(thisArg,[argsArray])

Whenever you add a method to a new object, sometimes you have to override a method for it. If you use apply, you only need to write the method once, and then inherit it in the new object, which is very convenient.
The apply method is very similar to the call method, only the parameters are different. But just because of this, we don't need to know the specific parameters of the called object when using apply. We can only wear arguments, so the called object will be responsible for the arguments of the handle bottom touch.
1. Like Java, we can use apply to create a construction chain for an object. In the following example, we will create a global method named construct, which can pass an array of parameters instead of one parameter.

// Function.prototype.construct = function(aArgs) {
//   var oNew = Object.create(this.prototype);
//   this.apply(oNew, aArgs);
//   return oNew;
// };

//Function.prototype.construct = function(aArgs) {
//  var fConstructor = this, fNewConstr = function() { 
//    fConstructor.apply(this, aArgs); 
//  };
// fNewConstr.prototype = fConstructor.prototype;
//  return new fNewConstr();
//};

Function.prototype.construct = function (aArgs) {
  var fNewConstr = new Function("");
  fNewConstr.prototype = this.prototype;
  var oNew = new fNewConstr();
  this.apply(oNew, aArgs);
  return oNew;
};
function MyConstructor() {
  for (var nProp = 0; nProp < arguments.length; nProp++) {
    this['property' + nProp] = arguments[nProp];
  }
}
var myArray = [4, 'Hello world!', false];
var myInstance = MyConstructor.construct(myArray);
console.log(myInstance.property1);                // logs 'Hello world!'
console.log(myInstance instanceof MyConstructor); // logs 'true'
console.log(myInstance.constructor);  
function minOfArray(arr){
    var min = Infinity;
    var QUANTUM = 32768;
    var len=arr.length;
    for(var i=0;i<len;i+=QUANTUM){
        var submin = Math.min.apply(null,arr.slice(i,Math.min(i+QUANTUM,len)));
        min = Math.min(submin,min)
    }
    return min;
}
var min = minOfArray([5,6,2,3,7]);
console.log(min)//2
    function Person(name,age)  
    {  
        this.name=name;  
        this.age=age;  
    }  
    /*Define a student class*/  
    function Student(name,age,grade)  
    {  
        Person.apply(this,arguments);  
        this.grade=grade;  
    }  
    //Create a student class  
    var student=new Student("zhangsan",21,"first grade");  
    //test  
    alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);  

Posted by jaret on Mon, 02 Dec 2019 08:58:45 -0800