javascript - How to write a object oriented Node.js model -
i having lot of trouble writing object oriented cat class in node.js. how can write cat.js class , use in following way:
// following 10 lines of code in file "app.js" outside // folder "model" var cat = require('./model/cat.js'); var cat1 = new cat(12, 'tom'); cat1.setage(100); console.log(cat1.getage()); // prints out 100 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 how fix following cat.js class have written:
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; };
if design object this, have done this
function cat(age, name) { // accept name , age in constructor this.name = name || null; this.age = age || null; } cat.prototype.getage = function() { return this.age; } cat.prototype.setage = function(age) { this.age = age; } cat.prototype.getname = function() { return this.name; } cat.prototype.setname = function(name) { this.name = name; } cat.prototype.equals = function(othercat) { return othercat.getname() == this.getname() && othercat.getage() == this.getage(); } cat.prototype.fill = function(newfields) { (var field in newfields) { if (this.hasownproperty(field) && newfields.hasownproperty(field)) { if (this[field] !== 'undefined') { this[field] = newfields[field]; } } } }; module.exports = cat; // export cat function and can used this
var cat = require("./cat.js"); var cat1 = new cat(12, 'tom'); cat1.setage(100); console.log(cat1.getage()); // 100 var cat2 = new cat(100, 'jerry'); console.log(cat1.equals(cat2)); // false var sameascat1 = new cat(100, 'tom'); console.log(cat1.equals(sameascat1)); // true var sameascat2 = new cat(); console.log(cat2.equals(sameascat2)); // false sameascat2.fill({name: "jerry", age: 100}); console.log(cat2.equals(sameascat2)); // true
Comments
Post a Comment