Define privileged methods Methods defined through the this keyword inside the constructor can be called by the instantiated object inheritance.
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('zhangsan');
s1.getName(); //zhangsan
The role of privileged methods Privileged methods can be publicly accessed outside the constructor (limited to instantiated objects), and can also access private members and methods, so they are used as objects or constructors The interface is most suitable. Through privileged methods, we can control the access of public methods to private properties or methods. There are many applications in the extension of JS framework.
The difference between privileged methods and public methods Same points: 1. Both can be publicly accessed outside the constructor. 2. All can access public properties
Differences: There are 2 points
1. Each instance must have a copy of the privileged method (except when used in a singleton, memory needs to be considered), while public methods Share
//Create Student object instance
var s1 = new Student('zhangsan');
var s2 = new Student('lisi');
//The references of the privileged methods of the two instances are different, indicating that the privileged methods are used when the object is instantiated. Recreated
console.log(s1.getName === s2.getName); //false
2. Privileged methods can access private properties and methods, but public methods cannot.
//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: Privileged methods serve as the interface of the constructor. Public methods can access private properties and methods through privileged methods.