Re: [問題] javascript 的 private 屬性
※ 引述《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
02/23 16:45, 1F
→
02/23 16:46, , 2F
02/23 16:46, 2F
→
02/23 16:47, , 3F
02/23 16:47, 3F
→
02/23 16:47, , 4F
02/23 16:47, 4F
→
02/23 16:47, , 5F
02/23 16:47, 5F
→
02/23 16:47, , 6F
02/23 16:47, 6F
→
02/23 16:48, , 7F
02/23 16:48, 7F
→
02/23 16:49, , 8F
02/23 16:49, 8F
→
02/23 16:49, , 9F
02/23 16:49, 9F
→
02/23 16:50, , 10F
02/23 16:50, 10F
→
02/23 16:51, , 11F
02/23 16:51, 11F
→
02/23 16:51, , 12F
02/23 16:51, 12F
→
02/23 16:51, , 13F
02/23 16:51, 13F
→
02/23 16:54, , 14F
02/23 16:54, 14F
→
02/26 12:53, , 15F
02/26 12:53, 15F
推
02/27 17:50, , 16F
02/27 17:50, 16F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 4 之 5 篇):