Re: [問題] javascript 的 private 屬性

看板Ajax作者 (大嘴先生)時間11年前 (2013/02/22 17:55), 編輯推噓1(1015)
留言16則, 3人參與, 最新討論串4/5 (看更多)
※ 引述《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

02/23 16:45, , 1F
剛剛試了一下 instance.__secret 輸出還是 1
02/23 16:45, 1F

02/23 16:46, , 2F
如果沒錯的話 加雙底線 並不是實際有 private 的效果
02/23 16:46, 2F

02/23 16:47, , 3F
原本是0 add一次後變成1沒錯啊?
02/23 16:47, 3F

02/23 16:47, , 4F
對 不是實際有pricate的效果
02/23 16:47, 4F

02/23 16:47, , 5F
這是在 Python 裡的一種 convention (不知道怎樣翻比較正確)
02/23 16:47, 5F

02/23 16:47, , 6F
前面推文有說了 單純就是一種像註解的宣告
02/23 16:47, 6F

02/23 16:48, , 7F
要真正private 在js只能靠var跟巢狀function
02/23 16:48, 7F

02/23 16:49, , 8F
嗯 這個就是看原發問人的需求了...
02/23 16:49, 8F

02/23 16:49, , 9F
在"會有很多實例"或"此class有很多method"的狀況下極佔
02/23 16:49, 9F

02/23 16:50, , 10F
資源...這也是目前各大lib都是用__當私有變數的原因
02/23 16:50, 10F

02/23 16:51, , 11F
不過自己設計SPA app時....其實還是可以用巢狀fn啦
02/23 16:51, 11F

02/23 16:51, , 12F
喔 看到你一開始寫的話了, 的確就是通融作法...
02/23 16:51, 12F

02/23 16:51, , 13F
大部份情形下user的瀏覽器都是能滿足要求的
02/23 16:51, 13F

02/23 16:54, , 14F
喔 補充一下 Python 的 __ 還是有實際效果的..真的是 private
02/23 16:54, 14F

02/26 12:53, , 15F
Python 只是會改名字而已,真的要拿還是拿得到
02/26 12:53, 15F

02/27 17:50, , 16F
嗯..
02/27 17:50, 16F
文章代碼(AID): #1H9q2Yz9 (Ajax)
討論串 (同標題文章)
文章代碼(AID): #1H9q2Yz9 (Ajax)