如何从该模型的实例调用静态 Backbone.Model 函数,而不指定模型名称?
我想从 Backbone.Model 对象的实例访问静态属性。我知道我可以对父构造函数进行硬编码来调用该方法,但这会阻止我拥有多态静态函数。例如,如果需要,我希望能够覆盖 ExtendedInventory
中的 foo
函数,而无需更改任何其他代码。
var Inventory = Backbone.Model.extend({},
//STATIC
{
foo: function() {
alert('bar');
}
});
var i = new Inventory({});
i.constructor.foo(); //This works!
var ExtendedInventory = Inventory.extend({});
var ei = new ExtendedInventory({});
ei.constructor.foo(); //THIS DOES NOT WORK
//How do I generically access the `Inventory.foo()` function via the `ei` object. I would
I have static properties that I would like to access from instances of my Backbone.Model objects. I know I could hardcode the parent constructor to call the method, but this prevents me from having polymorphic static functions. For example, I would like to be able to override the foo
function in ExtendedInventory
if necessary, without having to change any other code.
var Inventory = Backbone.Model.extend({},
//STATIC
{
foo: function() {
alert('bar');
}
});
var i = new Inventory({});
i.constructor.foo(); //This works!
var ExtendedInventory = Inventory.extend({});
var ei = new ExtendedInventory({});
ei.constructor.foo(); //THIS DOES NOT WORK
//How do I generically access the `Inventory.foo()` function via the `ei` object. I would
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
唔。尽管上面的代码确实有效,但我不会就这样。如果该函数在逻辑上可以通过类的对象访问,则在基类中定义一个调用该类/“静态”函数的实例方法。我认为这使得代码更干净、更清晰(另外,客户不必记住有些晦涩的语法):
Hmm. Though the code above does work, I wouldn't leave it that way. If the function is logically accessible through an object of the class, then define an instance method in the base class that calls the class/"static" function. This makes the code cleaner and clearer, I think (plus, clients don't have to remember the somewhat arcane syntax):
在你的例子中,什么不起作用?在 Firefox 和 IE 中,我都会看到两个带有“bar”的弹出窗口,这看起来像预期的结果吗?它的静态部分似乎也表现良好,请参阅this jsfiddle。
(这是 Backbone 的 HEAD 版本,顺便说一句;不知道这是否有区别)
What doesn't work exactly, in your example? In both Firefox and IE, I get two popups with 'bar', which looks like the intended result? The static part of it appears to behave fine as well, see this jsfiddle.
(this is with the HEAD version of Backbone, btw; don't know if that makes a difference)