JavaScript 构造函数原型
我正在尝试使用下划线和 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。可能是什么问题?
I'm trying to build a similar version of Rails ActiveRecord in Javascript, using underscore and Mongodb. 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. What might be the problem?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
从对象实例中,可以通过constructor.prototype 属性访问原型。
所以,one.constructor.prototype === Client.prototype。
看来您只是检查了错误的属性,应该是
one.constructor.prototype
,而不是one.prototype
。另请查看
__proto__
实例对象的属性。From an object instance, the prototype is accessible via the
constructor.prototype
property.So,
one.constructor.prototype === Client.prototype
.It seems your are just checking the wrong property, should be
one.constructor.prototype
, notone.prototype
.Also have a look at the
__proto__
property of an instance object.