Skip to content

Commit 4edfdbf

Browse files
committed
私有属性和方法 之 私有成员 翻译完毕
1 parent b2094bf commit 4edfdbf

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

chapter5.markdown

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,3 +171,49 @@ JavaScript库往往是模块化而且有用到命名空间的,这使用你可
171171
minified test2 body:
172172
var a=MYAPP.modules;alert(a.m1);alert(a.m2);alert(a.m51)
173173
*/
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+

0 commit comments

Comments
 (0)