动态创建对象实例的约定是什么? [英] What is the convention for dynamically creating an object instance?
问题描述
我正在创建一个可以让您放置多个小部件的页面,并且可以在页面上复制一些小部件。所以我需要了解在运行中创建对象实例的正确惯例。
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?
谢谢。
推荐答案
在JavaScript中,我们使用函数(所谓的构造函数)来实例化对象实例。
In JavaScript, we use functions (so called constructor functions) to instantiate object instances.
function Bulb() {
this.state = 0;
}
// one instance
var bulb1 = new Bulb();
// another instance
var bulb2 = new Bulb();
您的代码不起作用,因为您的 bulb
是一个常规对象而不是一个函数,所以你不能调用它(你试图用 bulb()
)
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 with bulb()
).
更新:您可以将实例存储到Array全局变量中: p>
Update: You could store your instances into an Array global variable:
var bulbs = [];
然后,只要您创建一个新实例,只需确保将其放在Array 。
And then, whenever you create a new instance, just just make sure that you put it in the Array.
$('button').click(function() {
var bulb = new Bulb();
// do stuff with bulb
// make sure to store it into the Array
bulbs.push(bulb);
});
您可以随时访问这些实例:
You can access the instances at any time like so:
bulbs[0] // the 1. instance
bulbs[1] // the 2. instance
// etc.
这篇关于动态创建对象实例的约定是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!