我目前正在使用以下模式来创建要使用的JS模块。但是,我无法弄清楚在第一种风格和第二种风格中这样做是否有任何区别或任何好处。
第一种方式
var UI = UI || {};
(function () {
var BtnShape = function (x, y, width, height, size, color, text)
{
this.initialise(x, y, width, height, size, color, text);
}
var p = BtnShape.prototype;
p.isEnabled = false; //<--------------
p.initialise = function (x, y, width, height, size, color, text)
{}
UI.BtnShape = BtnShape;
})();
第二种方式
var UI = UI || {};
(function () {
var BtnShape = function (x, y, width, height, size, color, text)
{
this.initialise(x, y, width, height, size, color, text);
}
var p = BtnShape.prototype;
p.initialise = function (x, y, width, height, size, color, text)
{
this.isEnabled = false; //<---------------
}
UI.BtnShape = BtnShape;
})();
我在这里可以看到的唯一区别是isEnabled
属性的设置顺序。通过将 isEnabled
属性嵌套到 initialise 函数中,您需要在isEnabled
具有任何值之前运行 initalise
过程。我假设您会在执行任何操作之前运行初始化函数,但是如果您不这样做,那么isEnabled
将是空的。
一种方式:无论您是否拨打initialise()
,isEnabled
都将false
。
第二种方式:只有当您调用initialise()
时,isEnabled
才会false
,undefined
其他方式。
首先,默认情况下未启用(但未定义)
// After all your code
var x= BtnShape.prototype;
// Here x is not enabled . If you want to enable it, you need to do it separately like below.
p.isEnabled = true;
第二种方式,当您初始化对象时,默认情况下它会变为 false。除非,你初始化,如果你初始化,它就会被拨打。您需要单独启用它。
var y =BtnShape.prototype;
// Here if you don't initialize the object y, then isEnabled is undefined.