【发布时间】:2015-08-24 06:23:39
【问题描述】:
拿这个类似问题的列表:
- How to set up JavaScript namespace and classes properly
- Javascript namespace declaration with function-prototype
- Best OOP approach to these two small JavaScript classes
我得出的结论是,在 JS 中实现 类 和 实例 有两种可能的方法:使用内部函数或使用原型。
因此,假设我们在命名空间 BOX_LOGIC 中有一个 Box 类,其中包含一个简单的代码。我可以编写以下代码:
BOX_LOGIC.Box = (function() {
// private static
var boxCount = 0;
var classDefinition = function(x) {
x = x || 0;
var capacity = x;
var id = ++boxCount;
// public methods
this.getCapacity = function() { return capacity; };
this.getId = function() { return id; };
this.add = function(weight) {
weight = weight || 0;
if (capacity >= weight) {
capacity -= weight;
}
return capacity;
};
};
return classDefinition;
})();
以及我能够编码:
BOX_LOGIC.Box = (function () {
var boxCount;
var Box= function (x) {
x = x || 0;
this.capacity = x;
this.id = ++boxCount;
};
Box.prototype = {
Constructor: Box,
add: function (weight) {
weight = weight || 0;
if (this.capacity >= weight) {
this.capacity -= weight;
}
return this.capacity;
}
};
return Box;
})();
我的问题是:使用 Box 原型 到底有什么区别?出于任何原因(成本、易读性、标准......),有什么方法更好吗?
第二种方法是否可以模拟static idvariable? THX!
【问题讨论】:
-
@T.J.Crowder 打错字,已更正
-
getCapacity在您的第二个示例中毫无用处。在您的第一个中,我更喜欢使用吸气剂。值得注意的是,这两种方法并不相互排斥,而是可以结合使用。
标签: javascript oop closures prototype