仅将模型定义为简单 js 的可能后果是什么
对象,并在必要时使用基于原型的继承?
IMO,随着时间的推移,随着应用程序大小的增加或团队规模的增加,随着许多开发人员开始处理相同的代码,您将失去可维护性。
换句话说 - 如果没有适当的封装,很容易修改不属于自己的对象 - 很容易干预你不想被触摸的部分。
如果您正在编写某种库/框架,其中只有 API 向用户公开,而您没有适当的封装,则可能仅通过一次修改就可以降低所有内容。
例如:
var myObj = {
mySecretPrivateCrucialFunction: function () {
// all the awesome crucial logic
},
//This is what you want other parts of the code ...
// ... to be interacting with in this object
myPublicMethod: function () {
// some logic
mySecretPrivateCrucialFunction();
// some thing else
}
}
我能做到。
myObj.mySecretPrivateCrucialFunction = function () {
alert('yay..i got you..');
};
但如果你这样做 - 你不会给那个机会。
var myObj = (function () {
var mySecretPrivateCrucialFunction = function () {
// all the awesome crucial logic
}
//This is what you want other parts of the code ...
// ... to be interacting with in this object
return {
myPublicMethod: function () {} /*some logic */
mySecretPrivateCrucialFunction(); /*some thing else */
}
})();
如果您想将所有属性隐藏/私有,但仍想获取对象的 JSON 表示 - 您可以执行以下操作 -
var myObj = (function () {
// your private properties
var prop1 = 1;
var prop2 = 2;
// your getters
var getProp1 = function () {
return prop1;
};
var getProp2 = function () {
return Prop2;
};
// your setters
var setProp1 = function (newValue) {
prop1 = newValue;
};
var setProp2 = function (newValue) {
prop2 = newValue;
};
// your JSON representation of the object
var toString = function () {
return JSON.stringify({
prop1: prop1,
prop2: prop2
});
};
// Object that gets exposed -
return {
"getProp1": getProp1,
"getProp2": getProp2,
"setProp1": setProp1,
"setProp2": setProp2,
"toString": toString
}
})();