Home > Web Front-end > JS Tutorial > Understand the call and apply_javascript techniques of Javascript

Understand the call and apply_javascript techniques of Javascript

WBOY
Release: 2016-05-16 15:25:20
Original
1342 people have browsed it

The call method calls a function or method using a specified this value and several specified parameter values.

Note: The syntax of this function is almost identical to that of the apply() method. The only difference is that the apply() method accepts a parameter array, while the call The () method accepts a list of parameters.

After understanding the concepts of these two methods, let’s understand their applications step by step.

Change the pointer of this in the method
Let’s first look at the following example

var name = "编程的人";
var age = 1;
var person = {
name:"公众号:bianchengderen",
age:20
}
function say(){
console.log("我叫:"+this.name+",年龄:"+this.age)
}
say();// 我叫: 编程的人,年龄: 1
say.call(person);//年龄:20

Copy after login

The execution methods of these two calls are different, and their results are also different. The difference is that this in the say method points to different objects. The first execution points to the window, and we execute it in call mode. Point this in the say method to the person object.
Doesn’t this feel a bit like pretending to be someone else? So what’s the use of this? Of course, you can think more about what you can do! Let’s continue going down.

Implement inheritance mechanism
Inheritance, this is a feature of advanced object-oriented. Using call, we can use JAVASCRIPT to have this feature.
Before looking at the following example, you must have a good understanding of the above example.

function Person(){
this.name = "编程的人";
this.age = 20;
}
function Student(){
Person.call(this);
this.school = "地球";
}
var student = new Student();
//下面打印出来: 编程的人,20,地球
console.log(student.name,student.age,student.school);

Copy after login

In this example, the Student function inherits the name and age attributes of Person, which is implemented through Person.call(this). After understanding the above example, it should not be difficult to understand. So Student has Person’s characteristics, and has its own personality, such as this.school.

Here, we do not involve adding parameters to pass. It is to facilitate everyone’s understanding. We need to add parameters to pass. You can try the code and see how it works!

Let’s talk about these two examples first, and then study in depth.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template