The method defined by the this keyword inside the constructor is a privileged method. It serves to make public access outside the constructor (only for instantiated objects), and also to access private members and methods, if you are interested, refer
Define privileged Methods
Within the constructor, a method defined by the this keyword can be called by inheriting the instantiated object.
The Code is as follows:
Var Student = function (name ){
Var _ name = name; // Private Attribute
// Privileged method
This. getName = function (){
Return _ name;
};
This. setName = function (name ){
_ Name = name;
};
};
Var s1 = new Student ('hangsan ');
S1.getName (); // zhangsan
Role of privileged Methods
Privileged methods can be publicly accessed outside the constructor (only for instantiated objects), and private members and methods can be accessed. Therefore, the interface used as an object or constructor is the most suitable, through the privileged method, we can control access to private attributes or methods by the public method. There are many applications in JS framework extension.
Differences between privileged and public methods
Similarities: 1. Public access is allowed outside the constructor. 2. All public attributes can be accessed.
Differences: there are two points
1. Each instance must have a copy of the privileged method (in addition to the use in a single instance, memory needs to be considered), while the public method is shared by all instances.
The Code is as follows:
// Create a Student object instance
Var s1 = new Student ('hangsan ');
Var s2 = new Student ('lisi ');
// The reference of the privileged methods of the two instances is different, indicating that the special permission method is re-created when the object is instantiated.
Console. log (s1.getName === s2.getName); // false
2. Privileged methods can access private attributes and methods, but public methods cannot.
The Code is as follows:
// Create a public method for Student
// Public methods cannot access private attributes
Student. prototype. myMethod = function (){
Console. log (_ name); // ReferenceError: _ name is not defined
};
S1.myMethod ();
Summary: The privileged method acts as the interface of the constructor. The public method can access private attributes and methods through the privileged method.