动态创建对象实例的约定是什么?
我正在创建一个页面,允许您在其上放置多个小部件,并且某些小部件可以在页面上重复。所以我需要了解动态创建对象实例的正确约定。
// my bulb object
var bulb = {
state: 0
};
// programatically, hard-coded instance name of 'bulb1'
var bulb1 = new bulb();
$('button').click(function() {
// create another new bulb instance here with dynamic name
});
或者我只是一起走上了错误的道路?
谢谢。
I'm creating a page that will allow you to put multiple widgets on it, and some widgets can be duplicated on the page. So I need to understand the proper convention for creating an object instance on the fly.
// my bulb object
var bulb = {
state: 0
};
// programatically, hard-coded instance name of 'bulb1'
var bulb1 = new bulb();
$('button').click(function() {
// create another new bulb instance here with dynamic name
});
Or am I just going down the wrong path all together?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在 JavaScript 中,我们使用函数(所谓的构造函数)来实例化对象实例。
您的代码不起作用,因为您的
bulb
是常规对象而不是函数,因此您无法调用它(您正尝试使用bulb()
来调用它)。更新:您可以将实例存储到数组全局变量中:
然后,每当您创建新实例时,只需确保将其放入数组中即可。
您可以随时访问实例,如下所示:
In JavaScript, we use functions (so called constructor functions) to instantiate object instances.
Your code doesn't work because your
bulb
is a regular object and not a function, so you cannot call it (which you are trying to do withbulb()
).Update: You could store your instances into an Array global variable:
And then, whenever you create a new instance, just just make sure that you put it in the Array.
You can access the instances at any time like so: