簡體   English   中英

JavaScript構造函數原型

[英]Javascript constructor prototype

我正在嘗試使用下划線和Mongodb使用Javascript構建類似版本的Rails ActiveRecord。 關於新創建的對象可以從類的構造函數繼承其原型的方式,我無法解決。 也許如果我說明我的觀點,那會更容易:

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。 可能是什么問題?

通過對象實例,可通過constructor.prototype .prototype屬性訪問原型。

因此, one.constructor.prototype === Client.prototype

看來您只是在檢查錯誤的屬性,應該是one.constructor.prototype ,而不是one.prototype

還可以查看實例對象的__proto__屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM