Re: [問題] javascript 的 private 屬性

看板Ajax作者 (海獅)時間11年前 (2013/02/22 17:29), 編輯推噓1(106)
留言7則, 2人參與, 最新討論串2/5 (看更多)
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應該不太一樣,所以有點困惑中 但應該有個對應的做法 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.133.61.45

02/22 17:44, , 1F
大師的作法符合的嚴格的物件導向要求 但卻犧牲了效能跟簡潔
02/22 17:44, 1F

02/22 17:45, , 2F
所以我覺得折衷的底線宣告法 應該是現在最好的方式 還有一
02/22 17:45, 2F

02/22 17:46, , 3F
般提到 getter/setter 都會想到是 1.public 2.called from
02/22 17:46, 3F

02/22 17:47, , 4F
outside client 所以你提到 getter/setter 會讓人有點誤會
02/22 17:47, 4F

02/22 17:54, , 5F
因為網頁中你所謂的 setter/getter 是內部使用並不開放
02/22 17:54, 5F

02/22 17:55, , 6F
大師也沒有使用getter/setter 而是以private method 稱呼它
02/22 17:55, 6F

02/22 18:09, , 7F
恩了解~ 加底線真的是個很輕鬆的解法
02/22 18:09, 7F
文章代碼(AID): #1H9pgEMj (Ajax)
討論串 (同標題文章)
文章代碼(AID): #1H9pgEMj (Ajax)