Home  >  Article  >  Web Front-end  >  JS privileged method definition function and the difference from public methods_javascript skills

JS privileged method definition function and the difference from public methods_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:40:201275browse
Define privileged methods
Methods defined through the this keyword inside the constructor can be called by the instantiated object inheritance.
Copy code 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('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
Copy code for all instances The code is as follows:

//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.
Copy code The code is 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: Privileged methods serve as the interface of the constructor. Public methods can access private properties and methods through privileged methods.
Statement:
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