Javascript: apply() function, call() function

Both apply() method and call() method can hijack the method of another object and inherit the properties of another object

One, apply() method

Function.apply(obj,args)

  • obj: Function This object class will replace this object, that this could have been directed Function now point to the obj;
  • args: This is an array, which will be passed to Function as an argument (args–>arguments)
var person = {
    
    
    fullName: function() {
    
    
        return 'fullName = ' + this.firstName + " " + this.lastName;
    }
}

var student = {
    
    
    firstName: "Bill",
    lastName: "Gates",
}
person.fullName.apply(student);  // 将返回 "Bill Gates"
var person = {
    
    
  fullName: function(city, country) {
    
    
    return 'fullName = ' + this.firstName + " " + this.lastName + ";address = " + city + "," + country;
  }
}
var student = {
    
    
  firstName:"John",
  lastName: "Doe"
}
person.fullName.apply(student , ["Oslo", "Norway"]);

Two, call() method

Function.call(obj,arg1,arg2…)

  • obj: Function This object class will replace this object, that this could have been directed Function now point to the obj;
  • arg1/arg2: It will be passed to Function as an argument (arg–>argument)
var person = {
    
    
  fullName: function(city, country) {
    
    
    return 'fullName = ' + this.firstName + " " + this.lastName + ";address = " + city + "," + country;
  }
}
var student = {
    
    
  firstName:"John",
  lastName: "Doe"
}
person.fullName.call(student, "Oslo", "Norway");

Three, the difference between call() and apply()

The call() method accepts parameters "respectively".

The apply() method accepts parameters in the form of an array.

If you want to use an array instead of a parameter list, the apply() method is very convenient.

Guess you like

Origin blog.csdn.net/u013250861/article/details/113622133