我不确定我是否正确理解了耦合。有人告诉我,如果我将数据移出到外部数据文件(如JSON)中,总体上会减少耦合。(我同意这一点。)
但是,如果我创建一个对象来保存JSON中包含的数据,那么JSON的字段将直接映射到JSON的结构,这不是仍然在对象和JSON之间创建了紧密耦合的链接吗?
例如:
"images": [{
"source" : "images/foo.png",
"size" : "thumbnail",
"alt" : "Foo"
},
{
"source" : "images/bar.png",
"size" : "thumbnail",
"alt" : "bar"
}]然后我们有一些对象,应用程序模型的一部分:
function FooBarImage (jsonObj) {
this.source = jsonObj.source;
this.size = jsonObj.size;
this.alt = jsonObj.alt;
}
FooBarImage.prototype.doStuff = function () { ... }在这里,FooBarImage对象知道JSON对象的内部格式。如果JSON数据的格式发生了变化(例如,我们想要添加一个新字段,或者重命名一个现有字段),难道我们不需要对构造函数进行更改吗?
我是不是误解了什么,或者有没有其他方法可以进一步解耦代码和数据?
发布于 2017-05-26 21:44:17
您可以很容易地“反映”/“映射”您的jsonObject (由所提供的JSON字符串的反序列化产生的文本对象)。您可以遍历对象属性并将其分配给您的实例:
function FooBarImage (jsonObj) {
Object.keys(jsonObj).forEach(function(prop) {
this[prop] = jsonObj[prop];
}
}
FooBarImage.prototype.doStuff = function () { ... }示例:
function dirtyMap(fromObj, toObj) {
Object.keys(fromObj).forEach(function(prop) {
toObj[prop] = fromObj[prop];
});
return toObj; // chain me?
};
function FooBarImage (jsonObj) {
dirtyMap(jsonObj, this);
};
FooBarImage.prototype.doStuff = function () {
console.log(this);
};
var json = `[{
"source" : "images/foo.png",
"size" : "thumbnail",
"alt" : "Foo"
},
{
"source" : "images/bar.png",
"size" : "thumbnail",
"alt" : "bar"
}]`
, images = JSON.parse(json)
, instances = images.map(function(img) { return new FooBarImage(img); })
;
instances.forEach(function(instance) { instance.doStuff(); });
另一种解决方案(当然还有其他解决方案)是使用工厂:
var createFooBarImage = function createFooBarImage(img) {
var fooBarImage = Object.create(img);
fooBarImage.doStuff = function () {
console.log(this);
};
return fooBarImage;
}示例:
var json = `[{
"source" : "images/foo.png",
"size" : "thumbnail",
"alt" : "Foo"
},
{
"source" : "images/bar.png",
"size" : "thumbnail",
"alt" : "bar"
}]`
, createFooBarImage = function createFooBarImage(img) {
var fooBarImage = Object.create(img);
fooBarImage.doStuff = function () {
console.log(this);
};
return fooBarImage;
}
, images = JSON.parse(json)
, instances = images.map(function(img) { return createFooBarImage(img); })
;
instances.forEach(function(instance) { instance.doStuff(); });
https://stackoverflow.com/questions/44202133
复制相似问题