File tree Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Expand file tree Collapse file tree 1 file changed +46
-0
lines changed Original file line number Diff line number Diff line change @@ -171,3 +171,49 @@ JavaScript库往往是模块化而且有用到命名空间的,这使用你可
171
171
minified test2 body:
172
172
var a=MYAPP.modules;alert(a.m1);alert(a.m2);alert(a.m51)
173
173
*/
174
+
175
+
176
+ ## 私有属性和方法
177
+
178
+ JavaScript不像Java或者其它语言,它没有专门的提供私有、保护、公有属性和方法的语法。所有的对象成员都是公有的:
179
+
180
+ var myobj = {
181
+ myprop: 1,
182
+ getProp: function () {
183
+ return this.myprop;
184
+ }
185
+ };
186
+ console.log(myobj.myprop); // `myprop` is publicly accessible console.log(myobj.getProp()); // getProp() is public too
187
+
188
+ 当你使用构造函数创建对象的时候也是一样的,所有的成员都是公有的:
189
+
190
+ function Gadget() {
191
+ this.name = 'iPod';
192
+ this.stretch = function () {
193
+ return 'iPad';
194
+ };
195
+ }
196
+ var toy = new Gadget();
197
+ console.log(toy.name); // `name` is public console.log(toy.stretch()); // stretch() is public
198
+
199
+ ### 私有成员
200
+
201
+ 尽管语言并没有用于私有成员的专门语法,但你可以通过闭包来实现。在构造函数中创建一个闭包,任何在这个闭包中的部分都不会暴露到构造函数之外。但是,这些私有变量却可以被公有方法访问,也就是在构造函数中定义的并且作为返回对象一部分的那些方法。我们来看一个例子,name是一个私有成员,在构造函数之外不能被访问:
202
+
203
+ function Gadget() {
204
+ // private member
205
+ var name = 'iPod';
206
+ // public function
207
+ this.getName = function () {
208
+ return name;
209
+ };
210
+ }
211
+ var toy = new Gadget();
212
+
213
+ // `name` is undefined, it's private
214
+ console.log(toy.name); // undefined
215
+ // public method has access to `name`
216
+ console.log(toy.getName()); // "iPod"
217
+
218
+ 如你所见,在JavaScript创建私有成员很容易。你需要做的只是将私有成员放在一个函数中,保证它是函数的本地变量,也就是说让它在函数之外不可以被访问。
219
+
You can’t perform that action at this time.
0 commit comments