Re: [問題] javascript 的 private 屬性

看板Ajax作者 (大嘴先生)時間11年前 (2013/02/22 17:49), 編輯推噓1(100)
留言1則, 1人參與, 最新討論串3/5 (看更多)
※ 引述《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 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 122.116.190.145 ※ 編輯: mrbigmouth 來自: 122.116.190.145 (02/22 17:54)

03/30 01:57, , 1F
說得很清楚
03/30 01:57, 1F
文章代碼(AID): #1H9pyDpN (Ajax)
討論串 (同標題文章)
文章代碼(AID): #1H9pyDpN (Ajax)