【问题标题】:How would I assign the prototype of Base to User?如何将 Base 的原型分配给 User?
【发布时间】:2012-09-10 19:15:05
【问题描述】:

我正在尝试拥有一个具有一些常用方法(保存、更新等)的 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
};

【问题讨论】:

    标签: javascript prototype appcelerator commonjs


    【解决方案1】:

    试试这个:

    User.prototype = new Base();
    

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

    【讨论】:

    • 感谢一个很棒的班轮。现在我真的很愚蠢,这很容易。
    • 嗯,没问题。我不得不问为什么 X 不起作用,然后被问到“如果它不应该是一个数组,为什么你在它周围有括号?”。我们都有这样的时刻。
    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-25
    • 2016-06-16
    • 1970-01-01
    • 2022-11-28
    • 2021-09-04
    相关资源
    最近更新 更多