我将如何将Base的原型分配给User

How would I assign the prototype of Base to User?

本文关键字:分配 User 原型 Base      更新时间:2023-09-26

我正在尝试创建一个Base对象,该对象具有一些常用方法(保存、更新等)。我尝试过使用Object.create(Base),但不知道如何使用module.exports

我将如何分配Base作为User的原型?或者有更好的方法来实现我的目标吗

models/user.js

var Base = require('models/base.js');
var User = module.exports = function(data) {    
    data       = data || {};    
    this.fname = data.fname || '';
    this.lname = data.lname || '';
    this.email = data.email || '';    
};
/**
 * Takes a response from FB and convert it to object
 */
User.prototype.importFacebookData = function(result) {
    this.fname      = result.first_name || '';
    this.lname      = result.last_name || '';
    this.name       = result.name || this.fname + ' ' + this.lname || '';
    this.email      = result.email || '';    
};

models/base.js

var Base = module.exports = function() {
};
Base.prototype.save = function() {
  // Some code for saving to DB
};

试试这个:

User.prototype = new Base();

不是在我现在可以测试的机器上,但理论上应该可以。