Home >Web Front-end >JS Tutorial >How to define private methods in javascript
The way JavaScript defines a private method is the function defined in the constructor of the class, which is a private method, and the code is [this.getSalary = function(){return salary;}].
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
How to define private methods in javascript:
Explanation: The function defined in the constructor of the class is a private method; and the function declared with var in the constructor Variables are also equivalent to private variables. (However, there are differences between the concept of private members in strongly typed languages such as C#. For example, they cannot be called in methods other than non-constructors)
Similarly, we can also implement things like set and get Attribute encapsulation
var Person = function(){ var salary = 0.0; this.setSalary = function(value){ salary = value; } this.getSalary = function(){ return salary; } } var p = new Person(); p.setSalary(1000); alert(p.getSalary());//返回1000 alert(p.salary);//返回undefined
Related free learning recommendations:javascript video tutorial
The above is the detailed content of How to define private methods in javascript. For more information, please follow other related articles on the PHP Chinese website!