JavaScript is actually an object-oriented language. In this way, the keyword "this" is particularly important within the class.
When creating a class, if you want each new class to have some common variables or other functions, this keyword is the best
.
Of course, since it is an object-oriented language, there must be a problem of access permissions, which is also closely related to the this keyword. The following is an example.
This section describes the access permissions of this class.
[Javascript]
// Person class
Function Person (){
Var name = "abc"; // var declares private variables inside the class and cannot be accessed from outside.
Var age = 20;
This. name2 = "edg"; // this declares public variables that can be accessed externally.
This. show = function () {// The shou method is a public method that can be accessed externally and can be a private internal method of the hosts class.
Window. alert (name );
}
Function show2 () {// The shouw2 method is a private method within the class and cannot be accessed externally.
}
}
Var p1 = new Person ();
Document. writeln (p1.name2 + p1.name );
P1.show ();
// Person class www.2cto.com
Function Person (){
Var name = "abc"; // var declares private variables inside the class and cannot be accessed from outside.
Var age = 20;
This. name2 = "edg"; // this declares public variables that can be accessed externally.
This. show = function () {// The shou method is a public method that can be accessed externally and can be a private internal method of the hosts class.
Window. alert (name );
}
Function show2 () {// The shouw2 method is a private method within the class and cannot be accessed externally.
}
}
Var p1 = new Person ();
Document. writeln (p1.name2 + p1.name );
P1.show ();
This Person is actually a class, and the class name is Person. The declared variables start with var and can only be accessed within the class.
Q, but the variables declared through the this keyword are public variables, which can be accessed externally. Of course, you only need to publish a method to implement external access.
This. show = function () {} declares a common method, which can be called outside the class. Of course
Similarly, the directly declared method is private/
Let's look at another example.
[Javascript]
Function test (){
Alert (this. v );
}
Var v = 902;
Window. test ();
Function test (){
Alert (this. v );
}
Var v = 902;
Window. test ();
The code is very short. this indicates who calls this method. this refers to the object, for example, the test method called by the window object,
Therefore, in the test method, this, v indicates whether a v variable is defined in the window, that is, the external world.
A var v = 902; therefore, this method is actually called the value of v.
From a352193394