2012-02-05 118 views
0

我想在Javascript中使用下划线和Mongodb构建类似版本的Rails ActiveRecord。有些东西我无法包装头,关于新创建的对象可以从类的构造函数继承其原型的方式。也许,如果我说明我的观点会更容易:Javascript构造函数原型

var root = this; 
var Database = root.Database = {}; 

// Require Underscore, if we're on the server, and it's not already present. 
var _ = root._; 
if (!_ && (typeof require !== 'undefined')) _ = require('./underscore'); 

Database.ActiveRecord = function(attributes){ 
    attributes || (attributes = {}); 
    this.attributes = {}; 
}; 

_.extend(Database.ActiveRecord.prototype, { 
    idAttribute: '_id', 
    test : 1, 
}); 


var Client = Database.ActiveRecord; 
var one = new Client(); 
console.log(one.prototype); 

的一个对象的原型不会继承Database.ActiveRecord.prototype。可能是什么问题?

回答

1

从对象实例中,可以通过constructor.prototype属性访问原型。因此,one.constructor.prototype === Client.prototype

看来你只是检查错误的属性,应该是one.constructor.prototype,而不是one.prototype

另请参见实例对象的__proto__属性。

+0

这是服务器端的东西。应该指定它。 – mabounassif 2012-02-05 04:17:11

+0

你其实是对的,这就是我称之为错误原型的方式。物业在那里。 – mabounassif 2012-02-05 04:18:25