gpt4 book ai didi

javascript - 主干和原型(prototype)初始化

转载 作者:行者123 更新时间:2023-11-28 13:50:13 26 4
gpt4 key购买 nike

我有一个代码:

Application = function() {
Application.prototype.currentQuote.collection.fetch();
};

Application.prototype = {}

Application.prototype.currentQuote = {};
Application.prototype.currentQuote.model = new (Backbone.Model.extend({
defaults: {
products: []
}
}))();

Application.prototype.currentQuote.collection = new (Backbone.Collection.extend({
model: Application.prototype.currentQuote.model,
url: 'test.json'
}))();

App = new Application();

但是,当获取集合时,我收到“Uncaught TypeError:对象不是函数”错误。我不明白为什么,我能解决什么问题?

您可以在此处查看测试用例:https://dl.dropbox.com/u/15806777/development/bb/index.html

谢谢!

最佳答案

我猜你的问题就在这里:

Application.prototype.currentQuote.collection = new (Backbone.Collection.extend({
model: Application.prototype.currentQuote.model, // <------------------------
url: 'test.json'
}))();

一个collection's model是:

the model class that the collection contains.

因此 model 应该来自 Backbone.Model.extend({...}) (即“类”),而不是来自new (Backbone.Model.extend({...})) (即模型实例)。当您要求集合创建一些模型(通过构造函数调用、fetchadd...)时,集合需要可以使用new 的东西 开启,您无法新 model_instance 因为 new operator needs a constructor function :

The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

这就是“Uncaught TypeError:对象不是函数”错误的来源。

你需要这样的东西:

Application.prototype.currentQuote.Model = Backbone.Model.extend({
defaults: {
products: []
}
});
//...
Application.prototype.currentQuote.collection = new (Backbone.Collection.extend({
model: Application.prototype.currentQuote.Model,
url: 'test.json'
}))();

关于javascript - 主干和原型(prototype)初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11375065/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com