我需要创建类似的东西:
var term = new Terminal();
每次我点击一个按钮。我发现我们可以在JavaScript中创建这样的动态变量:
window["term_" + _idContainer] = new Terminal({
cursorBlink: true,
});
但我不确定这一点,因为我只能使用我创建的最后一个。
所以有人可以告诉我它是否真的创建了动态var,以及每次创建它们时是否都不会被覆盖。
答案 0 :(得分:0)
您可以使用对象,而不会污染全局空间,例如
var collection = Object.create(null); // empty object without prototypes
// use
collection["term_" + _idContainer] = new Terminal({ cursorBlink: true });
答案 1 :(得分:0)
JavaScript对象实际上是字典式对象。因此,您可以通过以下两种方式向任何对象添加属性:
import UIKit
class ScoreClockViewController: UIViewController {
@IBOutlet weak var resetButton: UIButton!
@IBOutlet weak var okButton: UIButton!
var picker: ScoreClockPicker?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//Hide the Navigation Bar
self.navigationController?.setNavigationBarHidden(false, animated: true)
}
//@IBOutlet
@IBAction func reset(_ sender: Any) {
print("reset")
picker?.resetPicker() //Call the ScoreClockPicker
// picker?.selectRow(0, inComponent: 0, animated: true)
// picker?.selectRow(0, inComponent: 1, animated: true)
// picker?.selectRow(0, inComponent: 3, animated: true)
}
@IBAction func ok(_ sender: Any) {
}
}
因此,是的,您正在做的是在myobj.newProp = 'I am new!';
myobj['newProp2'] = 'So am I';
对象上创建一系列新属性。除非你忽略增量window
,否则没有理由会覆盖另一个。
我应该补充说,向_idContainer
对象添加变量并不是一件很受欢迎的事情,你可以通过这种机制添加很多变量。或许最好只添加一个,并根据需要进行扩展:
window