作者mrbigmouth (大嘴先生)
看板Ajax
标题Re: [问题] javascript 的 private 属性
时间Fri Feb 22 17:55:44 2013
※ 引述《mrbigmouth (大嘴先生)》之铭言:
: ※ 引述《BBSealion (海狮)》之铭言:
: : Private members are made by the constructor. Ordinary vars and parameters of
: : the constructor becomes the private members.
: : function Container(param) {
: : this.member = param;
: : var secret = 3;
: : var that = this;
: : }
: : This constructor makes three private instance variables: param, secret, and
: : that. They are attached to the object, but they are not accessible to the
: : outside, nor are they accessible to the object's own public methods.
: : by http://javascript.crockford.com/private.html
: : ---
: : 我知道private的用意就是保护变数不被乱动
: : 但另一个他该有的功能是: 在自己的method中能被使用
: : 不然我为了自己要用他就得开getter给他,如此变成您说的无意义了
: : 我想js的逻辑跟C应该不太一样,所以有点困惑中
: : 但应该有个对应的做法
: 用解释的很麻烦乾脆丢程式
: function ThisIsMyClass() {
: var secret = 0;
: this.methodAdd = function() {
: secret += 1;
: }
: this.getSecret = function() {
: return secret;
: }
: }
: var instance = new ThisIsMyClass();
: instance.methodAdd();
: instance.methodAdd();
: instance.methodAdd();
: instance.getSecret(); // 3
: instance.secret; // undefined
: 自己内部的method使用时不需要getter跟setter
: 只有给外部使用时才需要写getter跟setter
因为有人一直在强调别用巢状函式(其实我也建议太大的class别用巢状XD)
所以我再来试范一下用底线的方式
function MyClass() {
this.__secret = 0;
}
MyClass.prototype.methodAdd = function() {
this.__secret += 1;
}
MyClass.prototype.getScret = function() {
return this.__secret;
}
var instance = new MyClass();
instance.methodAdd();
instance.getScret(); //1
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 122.116.190.145
1F:→ wxyy:刚刚试了一下 instance.__secret 输出还是 1 02/23 16:45
2F:→ wxyy:如果没错的话 加双底线 并不是实际有 private 的效果 02/23 16:46
3F:→ mrbigmouth:原本是0 add一次後变成1没错啊? 02/23 16:47
4F:→ mrbigmouth:对 不是实际有pricate的效果 02/23 16:47
5F:→ wxyy:这是在 Python 里的一种 convention (不知道怎样翻比较正确) 02/23 16:47
6F:→ mrbigmouth:前面推文有说了 单纯就是一种像注解的宣告 02/23 16:47
7F:→ mrbigmouth:要真正private 在js只能靠var跟巢状function 02/23 16:48
8F:→ wxyy:嗯 这个就是看原发问人的需求了... 02/23 16:49
9F:→ mrbigmouth:在"会有很多实例"或"此class有很多method"的状况下极占 02/23 16:49
10F:→ mrbigmouth:资源...这也是目前各大lib都是用__当私有变数的原因 02/23 16:50
11F:→ mrbigmouth:不过自己设计SPA app时....其实还是可以用巢状fn啦 02/23 16:51
12F:→ wxyy:喔 看到你一开始写的话了, 的确就是通融作法... 02/23 16:51
13F:→ mrbigmouth:大部份情形下user的浏览器都是能满足要求的 02/23 16:51
14F:→ wxyy:喔 补充一下 Python 的 __ 还是有实际效果的..真的是 private 02/23 16:54
15F:→ legnaleurc:Python 只是会改名字而已,真的要拿还是拿得到 02/26 12:53
16F:推 wxyy:嗯.. 02/27 17:50