Home  >  Article  >  Web Front-end  >  How to define private methods in javascript

How to define private methods in javascript

coldplay.xixi
coldplay.xixiOriginal
2021-04-30 16:34:253193browse

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;}].

How to define private methods in javascript

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!

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