【发布时间】:2011-12-11 17:05:53
【问题描述】:
我目前正在用 javascript 编写对象,我想以一种清晰、漂亮的方式,使用最佳实践等。但我很困扰我必须总是写 this. 来处理属性,不像其他OO 语言。
所以我明白了 - 为什么不只对对象属性使用闭包?看看我的示例对象。所以代替这个,经典的方式:
var MyObjConstructor = function (a, b) {
// constructor - initialization of object attributes
this.a = a;
this.b = b;
this.var1 = 0;
this.var2 = "hello";
this.var3 = [1, 2, 3];
// methods
this.method1 = function () {
return this.var3[this.var1] + this.var2;
// terrible - I must always write "this." ...
};
}
...我会这样做使用闭包,然后我不需要每次都写this.来访问属性!
var MyObjConstructor = function (a, b) {
// constructor - initialization of object attributes
// the attributes are in the closure!!!
var a = a;
var b = b;
var var1 = 0;
var var2 = "hello";
var var3 = [1, 2, 3];
// methods
this.method1 = function () {
return var3[var1] + var2;
// nice and short
};
// I can also have "get" and "set" methods:
this.getVar1 = function () { return var1; }
this.setVar1 = function (value) { var1 = value; }
}
此外,它还有一个隐藏的好处,就是属性真的不能通过 get/set 方法以外的任何其他方式访问!!
所以问题是:
- 这是个好主意吗?它是否“干净”,是否符合最佳做法?
- 这两种解决方案之间是否存在其他语义差异?
- 有没有像这样使用闭包的陷阱?
【问题讨论】:
-
也许对象复制不起作用?
-
这是两个不同的东西 - 使用
this.prop定义公共属性,使用var prop定义私有属性。你不能用一个代替另一个,它们有不同的用途。 -
@ŠimeVidas
var prop定义了一个局部变量,只能在构造函数内部或在构造函数中定义的函数内部访问。private这个词具有误导性。
标签: javascript oop closures