我在Node.js中編寫面向對象的Cat類時遇到了很多麻煩。我怎麼能寫一個Cat.js類,並以下列方式使用它:如何編寫面向對象的Node.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'上返回'object'。如果你只是把它們賦值爲'undefined'並且通過'typeof()'來測試它,否則它會出現它應該像你期望的那樣行爲。 –
到底需要幫助的問題究竟是什麼? – jfriend00
你可能想看看[TidBits OoJs](https://github.com/najamelan/TidBits_Javascript_OoJs)。它是可靠的,並給你關於你可能夢寐以求的所有OO功能,除了以簡單和自然的語法進行多重繼承。 – nus