Pregunta

I am trying to create s Base Model and extend models from it, but when i call DataModel it calls the function of UsersModel...

This is how i do the call:

var model = new(require('../models/DataModel'));

module.exports = PrivateController.extend({
name : 'Wall',
content : null,
run : function(type, req, res){        
    model.get(function(err, result){
        //WHEN THIS GETS CALLED -> DISPLAYS 'users' and should me xyz from DataModel
    }

});

Base.js

module.exports = function(db) {
this.db = db;
};
module.exports.prototype = {
extend: function(properties) {
    var Child = module.exports;
    Child.prototype = module.exports.prototype;
    for(var key in properties) {
        Child.prototype[key] = properties[key];
    }
    return Child;
}

DataModel:

var Model = require("./Base"),
model = new Model();


var DataModel = model.extend({
    collection_name: 'xyz',
get: function(callback) {
    console.log(this.collection_name); // THIS SHOULD DISPLAY 'xyz'
}
});


 module.exports = DataModel;

Instead of showing DataModel collection name i get it from here:

UserModel.js

var Model = require("./Base"),
model = new Model();

var UserModel = model.extend({
collection_name: 'users',
get: function(callback, email, password) {
    console.log(this.collection_name); //DISPLAY users
},



module.exports = UserModel;
¿Fue útil?

Solución

I'm not sure where you got the code from for that extend function but it's horribly incorrect.

I've formatted it a bit better so we can see the issues:

var Base = function(db) {
    this.db = db;
};

Base.prototype = {
    extend: function(properties) {
        var Child = Base; // what?
        Child.prototype = Base.prototype; // what?
        for(var key in properties) {
            Child.prototype[key] = properties[key];
        }
        return Child;
    }
};

In your extend function:

You're setting the child object to be a reference to the super object, thus you're effectively changing the super object, thus all other objects that rely on the super prototype will be affected.

This is probably what you want to do:

var Base = function(db) {
    this.db = db;
};

Base.prototype = {
    extend: function(properties) {
        var Child = function(){
            Base.apply(this, arguments);
        };
        Child.prototype = Object.create(Base.prototype);
        for(var key in properties) {
            Child.prototype[key] = properties[key];
        }
        return Child;
    }
};

For inheritance in node.js, personally I would just stick with util.inherits. Have a read on Object.create to view more inheritance examples.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top