JavaScript 构造函数原型

发布于 2025-01-02 03:56:45 字数 721 浏览 2 评论 0原文

我正在尝试使用下划线和 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

〗斷ホ乔殘χμё〖 2025-01-09 03:56:45

从对象实例中,可以通过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, not one.prototype.

Also have a look at the __proto__ property of an instance object.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文