2012-02-05 211 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