Simply put, the context of function execution is changed, which is the most basic usage. The basic difference between the two methods is that parameter passing is different.
Call (obj, arg1, arg2, arg3); call the first parameter to pass the object, which can be null. The parameters are separated by commas (,). The parameters can be of any type.
Apply (obj, [arg1, arg2, arg3]); apply the first parameter to pass the object. The parameter can be an array or arguments object.
These two methods are usually used for class inheritance and callback functions:
Role 1: class inheritance:
Let's take a look at this example:
Copy codeThe Code is as follows:
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 ("yuren wharf", 28, "male ");
Test. alertName (); // Yu Ren 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 in this object, so webDever has all the attributes and methods of Person, the test object can directly call the Person Method and Its Attributes. The understanding in is very superficial.
Function 2: callback function:
Call and apply are also very useful in the number of callback rows. In many cases, we need to change the execution context of the callback function during development, such as ajax or timing. In general, ajax is global, that is, under the window object. Let's look at this example:
Copy codeThe Code is as follows:
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
Copy codeThe Code is as follows:
Album. get_owner (function (owner ){
Alert (The album '+ this. name + 'belongs to' + owner );
});
This. name in can directly obtain the name attribute in the album object.