我正在开发一个 Node.js 应用程序。寻找创建数据模型的方法。
发送到客户端或从客户端发送的数据是 JSON。由于数据库是 MongoDb,因此与数据库之间的数据是 JSON。
我是 JS 新手,我可以找到很多专门用于创建封装对象的 js 库。还需要吗?
仅将模型定义为简单的 js 对象并在必要时使用基于原型(prototype)的继承可能会产生什么结果?
感谢任何帮助。谢谢。
最佳答案
What are the possible consequence of just defining models as simple js objects, and use prototype based inheritance where necessary?
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 */
}
})();
如果您想要将所有属性隐藏/私有(private),并且仍然想要获取对象的 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
}
})();
关于javascript - JavaScript 对象需要封装吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14032370/