Home > Web Front-end > JS Tutorial > body text

How to define private methods in javascript

coldplay.xixi
Release: 2023-01-05 16:13:22
Original
2889 people have browsed it

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
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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 [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!