defining a Privileged method
The method defined by the This keyword inside the constructor can be invoked by the instantiated object inheritance.
Copy Code code as follows:
var Student = function (name) {
var _name = name; Private property
Privileged methods
This.getname = function () {
return _name;
};
This.setname = function (name) {
_name = name;
};
};
var S1 = new Student (' Zhangsan ');
S1.getname (); Zhangsan
the role of the privileged method
Privileged methods can be publicly accessed outside the constructor (only for instantiated objects), and access to private members and methods, so the interface used as an object or constructor is the most appropriate, and privileged methods allow us to control the access of public methods to private properties or methods. There are many applications in the expansion of JS framework.
the difference between a privileged method and a public method
Same point: 1. can be publicly accessed outside the constructor. 2. Access to public properties
Different points: there are 2 points
1. Each instance must have a copy of the privileged method (in addition to being used in a single case, memory is needed), while the public method shares all instances of the
Copy Code code as follows:
Create a Student object instance
var S1 = new Student (' Zhangsan ');
var s2 = new Student (' Lisi ');
The reference to the privileged method of the two instances is different, indicating that the privileged method was recreated when the object was instantiated
Console.log (S1.getname = = = S2.getname); False
2. Privileged methods can access private properties and methods, while public methods cannot.
Copy Code code as follows:
Create a public method for student
Public methods cannot access private properties
Student.prototype.myMethod = function () {
Console.log (_name); Referenceerror: _name is not defined
};
S1.mymethod ();
Summary: The privileged method acts as an interface to the constructor, and public methods can access private properties and methods through privileged methods