作者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