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

JavaScript object-oriented private members and public members_js object-oriented

WBOY
Release: 2016-05-16 18:27:38
Original
1176 people have browsed it

It's actually very simple, so don't talk nonsense. I believe you will understand it clearly after reading the code and comments below!

Copy code The code is as follows:

//Declare a class, which is actually a method in JavaScript , namespace, class, member... everything is an object
MyClass =function(){
var _this=this;
//Private variable
var aa="11";
//Public variable
this.bb="22";
//Private method
function fun1(){
alert(aa);
alert(_this.bb);
}
//Private method
var fun2=function(){
alert(aa);
alert(_this.bb);
}
//Public method
this.fun3=function(){
alert(aa);
alert(_this.bb);
}
}
//The test is as follows:
var mc =new MyClass();
mc.aa="AA";//Error
mc.bb="BB";//Correct
mc.fun1();//Error
mc .fun2();//Error
mc.fun3();//Correct


In a nutshell: declare with var keyword inside the class
The variables or methods are private;
The methods declared with the function keyword are private;
The variables or methods declared with the this keyword are public.

The above are all for instance classes, but for static classes it is even simpler. JavaScript static classes are actually a json object, so all its members are public. It is visible to the outside world!

Author: Uncle Xiang
Source: http://xumingxiang.cnblogs.com/
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 admin@php.cn
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!