简体   繁体   English

JavaScript构造函数原型

[英]Javascript constructor prototype

I'm trying to build a similar version of Rails ActiveRecord in Javascript, using underscore and Mongodb. 我正在尝试使用下划线和Mongodb使用Javascript构建类似版本的Rails ActiveRecord。 There is something that I can't wrap my head around concerning the way a newly created object can inherit his prototype from the constructor of the class. 关于新创建的对象可以从类的构造函数继承其原型的方式,我无法解决。 Maybe if I illustrate my point it would be easier: 也许如果我说明我的观点,那会更容易:

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);

The object one's prototype doesn't inherit the Database.ActiveRecord.prototype. 对象的原型不会继承Database.ActiveRecord.prototype。 What might be the problem? 可能是什么问题?

From an object instance, the prototype is accessible via the constructor.prototype property. 通过对象实例,可通过constructor.prototype .prototype属性访问原型。

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

It seems your are just checking the wrong property, should be one.constructor.prototype , not one.prototype . 看来您只是在检查错误的属性,应该是one.constructor.prototype ,而不是one.prototype

Also have a look at the __proto__ property of an instance object. 还可以查看实例对象的__proto__属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM