【发布时间】:2015-08-08 04:13:15
【问题描述】:
如果构造函数和它的原型定义在同一个模块中,比如 AMD 模块,是否可以将模块的类私有字段设为全局以便在原型中访问,而不是在构造函数中使用下划线定义它们?
这样更好吗:
define(function (require) {
"use strict";
var steps = 0;
function Constructor(_steps) {
steps = _steps;
}
Constructor.prototype.go = function () {
steps += 1;
};
然后这个:
define(function (require) {
"use strict";
function Constructor(_steps) {
this._steps = _steps;
}
Constructor.prototype.go = function () {
this._steps += 1;
};
?
【问题讨论】:
-
这两种解决方案是不同的。您无法比较它们,因为它们的行为不同。
-
也许你的意思是后者
Constructor.prototype._ = {}; function Constructor(_steps) { this._.steps = _steps; }? -
@Maximus 你创建了多个类的实例吗?如果是,它们是否共享相同的
steps变量值? -
如果是单例,那么没有理由使用构造函数。
-
@Maximus 但它没有正式的要求。一切基于约定的东西——都是基于约定的。您可能会得到一些有用的 cmets/answers,但它们并不能直接解决您的问题,因为只有您才能回答。
标签: javascript