作者mrbigmouth (大嘴先生)
看板Ajax
标题Re: [问题] javascript 的 private 属性
时间Fri Feb 22 17:48:58 2013
※ 引述《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)
1F:推 jojozyzy:说得很清楚 03/30 01:57