我一直在摆弄通过 Javascript(特别是 NodeJS)中的组合来构建对象,并且我想出了一种构建对象的方法,但我需要知道这是否是一种疯狂的做事方式。
简单的版本是这样的:我有两个对象,都有两个属性,一个包含一个数字,另一个包含一个字符串。
文件:Cat.js
function Cat() {
this.name = 'Fuzzy Whiskerkins';
this.owner = 'James';
}
module.exports = Cat;
文件:Car.js
function Car() {
this.color = 'blue';
this.owner = 'James';
}
module.exports = Car;
我现在想为这两个对象中的所有属性添加一个基本的 getter/setter 函数。我还希望能够检查传递给这些设置器的值是否与类型匹配。我没有为每个属性编写四个原型函数,而是执行了以下操作:
文件:StringProperty.js
module.exports = function(newObject, propertyName) {
newObject.prototype[propertyName] = function( newString ) {
if ( typeof newString !== 'undefined' ) {
if ( typeof newString !== 'string' ) {
return;
}
this.properties.[propertyName] = newString;
return this;
}
return this.properties.[propertyName];
}
}
文件:Cat.js
var StringProperty = require('./StringProperty.js');
function Cat() {
this.properties.name = 'Fuzzy Whiskerkins';
this.properties.owner = 'James';
}
StringProperty( Cat, 'name' );
StringProperty( Cat, 'owner' );
module.exports = Cat;
文件:Car.js
var StringProperty = require('./StringProperty.js');
function Car() {
this.properties.color = 'blue';
this.properties.owner = 'James';
}
StringProperty( Car, 'color' );
NumberProperty( Car, 'owner' );
module.exports = Car;
现在这两个对象都具备了它们需要的所有基本功能,并且我能够用最少的代码来完成它,并且每当我需要添加另一个字符串属性时,我必须添加的代码量将是最少的。
我疯了吗?这是一件疯狂的事情吗/有没有更好的方法来做到这一点?
编辑:我试图用这个来完成的是我正在处理的应用程序有 100 多个对象,每个对象都有 10 多个属性,并且必须为这些属性中的每一个都编写几乎完全相同的代码的想法设置得不好与我一起。我希望能够有一些代码来添加属性并创建 getter/setter 函数(添加用于属性限制分歧的选项,例如字符串属性的不同长度限制)。我已经查看了多个通过 JS 中的组合构建对象的示例,但我没有尝试过适合 NodeJS 模块结构。