如何仅在给定类名的情况下在运行时动态创建新的 Javascript 对象?
假设有一些小部件:
function Widget1(initData) {
....
}
Widget1.prototype.render = function() {
....
}
function Widget2(initData) {
....
}
Widget2.prototype.render = function() {
....
}
我需要做的是:
$.subscribe('/launch', function(widgetName, initData) {
// create a new object of the widget and then call the render method
});
我不想编写多个 if-else 块,因为小部件的数量可能会变得非常大。一种选择是使用 eval(),但我相信可能有更好的技术。我正在使用 JQuery 框架,因此不想包含任何其他可能具有支持此功能的特定功能的框架。纯 Javascript 解决方案将受到赞赏。
Let us say there are some widgets:
function Widget1(initData) {
....
}
Widget1.prototype.render = function() {
....
}
function Widget2(initData) {
....
}
Widget2.prototype.render = function() {
....
}
What I need to do is the following:
$.subscribe('/launch', function(widgetName, initData) {
// create a new object of the widget and then call the render method
});
I dont want to write multiple if-else blocks as the number of widgets may become very large. One option is to use eval(), but I believe that there may be better techniques. I am using JQuery framework, so don't want to include any other frameworks that may have a specific feature to support this. A pure Javascript solution will be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,有办法。当您创建函数时,它会被创建为该上下文中
this
对象的属性。因此,如果您在全局范围内声明这些 Widget 函数,它们就会成为window
对象的属性。您可能知道,您可以通过object.property
或object['property']
来访问属性。因此,如果它们是全球性的,您可以执行以下操作:编辑:正如 TJ Crowder 所说,我大错特错了。我所说的关于作为
this
的属性创建的函数适用于您位于全局范围内的情况(我想说“仅当您位于全局范围内时”,但因为我'我不是 100% 确定我会保持原样)。Yep, there is a way. When you create a function, it's created as a property of the
this
object in that context. So if you declare those Widget functions in the global scope, they become properties of thewindow
object. As you probably know, you can access a property both asobject.property
orobject['property']
. So, if they are global, you can do something like:EDIT: As T.J. Crowder said, I was horribly wrong. What I said about the function being created as a property of
this
applies when you're on the global scope (I want to say "only when you're on the global scope", but since I'm not 100% sure I'm gonna leave it as that).正如 Esalijia 的评论所说:
或者您可以使用
.bind()
来绑定
定义Widget*
的范围,并让它们可用于$.subscribe
方法。As the comment from Esalijia said:
Or you can
bind
the scope of whereWidget*
is defined using.bind()
and have them available to the$.subscribe
method.