【发布时间】:2014-05-02 17:55:36
【问题描述】:
我在 Node.js 中编写面向对象的 Cat 类时遇到了很多麻烦。如何编写一个 Cat.js 类并按以下方式使用它:
// following 10 lines of code is in another file "app.js" that is outside
// the folder "model"
var Cat = require('./model/Cat.js');
var cat1 = new Cat(12, 'Tom');
cat1.setAge(100);
console.log(cat1.getAge()); // prints out 100 to console
var cat2 = new Cat(100, 'Jerry');
console.log(cat1.equals(cat2)); // prints out false
var sameAsCat1 = new Cat(100, 'Tom');
console.log(cat1.equals(sameAsCat1)); // prints out True
您将如何修复我编写的以下 Cat.js 类:
var Cat = function() {
this.fields = {
age: null,
name: null
};
this.fill = function (newFields) {
for(var field in this.fields) {
if(this.fields[field] !== 'undefined') {
this.fields[field] = newFields[field];
}
}
};
this.getAge = function() {
return this.fields['age'];
};
this.getName = function() {
return this.fields['name'];
};
this.setAge = function(newAge) {
this.fields['age'] = newAge;
};
this.equals = function(otherCat) {
if (this.fields['age'] === otherCat.getAge() &&
this.fields['name'] === otherCat.getName()) {
return true;
} else {
return false;
}
};
};
module.exports = function(newFields) {
var instance = new Cat();
instance.fill(newFields);
return instance;
};
【问题讨论】:
-
这是否是唯一的问题,我不能说,但你想在你的
fill函数中测试typeof() !== 'undefined'。而且因为您为它们分配了null值,所以无论如何这都行不通,因为您将在typeof上获得“对象”。如果您只是将它们分配为undefined并通过typeof()进行测试,否则它看起来应该像您预期的那样运行。 -
您需要帮助的具体问题是什么?
-
您可能想看看TidBits OoJs。它是可靠的,并以简单自然的语法为您提供了您可能梦寐以求的所有 OO 功能,但多重继承除外。
标签: javascript node.js oop