Simply put, it is to change the context of function execution. This is the most basic usage. The basic difference between the two methods lies in the different parameters passed.
call(obj,arg1,arg2,arg3); The first parameter of call is an object, which can be null. Parameters are separated by commas and can be of any type.
apply(obj,[arg1,arg2,arg3]); The first parameter of apply is an object, and the parameter can be an array or arguments object.
These two methods are usually used for class inheritance and callback functions:
Function 1. Class inheritance:
Let’s look at this example first:
function Person(name,age){
this.name = name;
this.age=age;
this.alertName = function(){
alert(this.name);
}
this.alertAge = function(){
alert(this. age);
}
}
function webDever(name,age,sex){
Person.call(this,name,age);
this.sex=sex;
this.alertSex = function(){
alert(this.sex);
}
}
var test= new webDever("Fool's Wharf",28,"Male");
test.alertName();//Fool's Wharf
test.alertAge();//28
test.alertSex();//Male
In this way, the webDever class inherits the Person class , Person.call(this,name,age) means to use the Person constructor (also a function) to execute under this object, then webDever has all the attributes and methods of Person, and the test object can directly call Person's methods and Attribute; the understanding in 2009 was very superficial, haha.
Function 2. Callback function: call and apply are also very useful in callback lines. Many times we need to change the execution context of the callback function during the development process. The most commonly used ones are ajax or timing. Generally, Ajax is global, that is, under the window object. Let’s look at this example:
function Album(id, title, owner_id) {
this.id = id;
this.name = title;
this.owner_id = owner_id;
};
Album.prototype.get_owner = function (callback) {
var self = this;
$.get('/owners/' this.owner_id, function (data) {
callback && callback.call(self, data.name);
});
};
var album = new Album(1, 'life', 2);
album .get_owner(function (owner) {
alert('The album' this.name ' belongs to ' owner);
});
here
album.get_owner(function (owner) {
alert('The album' this .name ' belongs to ' owner);
});
This.name in
can directly get the name attribute in the album object.