Home > Article > Web Front-end > The difference between Javascript call and apply and how to use it_Basic knowledge
1. Definition of method
call method:
Syntax: fun.call(thisArg[, arg1[, arg2[, ...]]])
Definition: Call a method on an object to replace the current object with another object.
Note:
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 original context to the new object specified by thisArg.
If no thisArg parameter is provided, the Global object is used as thisArg.
apply method:
Syntax: fun.apply(thisArg[, argsArray])
Definition: Apply a method of an object and replace the current object with another object.
Note:
If argArray is not a valid array or is not an arguments object, a TypeError will be caused.
If neither argArray nor thisArg is provided, the Global object will be used as thisArg and no parameters can be passed.
2. The difference between the two
The basic difference between the two methods is that the parameters are passed differently
2.1. Call method:
function Food(name, price) {
Product.call(this, name, price);
this.category = 'food';
}
Food.prototype = new Product( );
function Toy(name, price) {
Product.call(this, name, price);
this.category = 'toy';
}
Toy.prototype = new Product( );
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
function Food(name, price) {
Product.apply(this, arguments);
this.category = 'food';
}
Food.prototype = new Product();
function Toy(name, price) {
Product.apply(this, arguments);
this.category = 'toy';
}
Toy.prototype = new Product();
var cheese = new Food('feta', 5);
var fun = new Toy('robot', 40);
3.1. Class inheritance
function webDever(name,age,sex){
Person.call(this,name,age);
this.sex=sex;
this.alertSex = function(){
alert(this.sex);
}
}
var test= new webDever("Design Hive",24,"Male");
test.alertName();//Design Hive
test.alertAge();//24
test .alertSex();//Male