Home >Web Front-end >JS Tutorial >Introduction to the use of call and apply in Javascript_javascript skills

Introduction to the use of call and apply in Javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:56:09933browse

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:

Copy code The 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("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:
Copy code The 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 code The code is as follows:

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.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn