ske*_*rit 5 javascript arrays oop class object
我刚刚发现了在javascript中创建假"类"的方法,但我想知道如何存储它们并且仍然可以在IDE中轻松访问它们的功能.
像这样:
function Map(){
this.width = 0;
this.height = 0;
this.layers = new Layers();
}
Run Code Online (Sandbox Code Playgroud)
现在我有一个循环遍历XML并创建多个Map()对象的函数.如果我将它们存储在单个变量下,我可以很好地访问它们,例如:
map1 = new Map();
map1.height = 1;
Run Code Online (Sandbox Code Playgroud)
但我不知道他们将以什么名字存储!所以我想我可以像这样保存它们:
mapArray = {};
mapArray['map1'] = new Map();
Run Code Online (Sandbox Code Playgroud)
但你无法访问这样的函数:(至少IDE代码完成不会捡起它)
mapArray['map1'].height = 1;
Run Code Online (Sandbox Code Playgroud)
然后我认为这将是最好的解决方案:
function fetch(name){
var fetch = new Map();
fetch = test[name];
}
Run Code Online (Sandbox Code Playgroud)
这样我就可以写:
fetch('test').height = 1;
Run Code Online (Sandbox Code Playgroud)
但这似乎会产生大量的开销,不断复制这样的变量.
我忽略了简单的事情吗?
它不起作用的原因是,为了让映射/数组允许其中包含任何内容,它必须假设里面的内容至多是继承树上非常低级的内容。不幸的是,Vector<>
与 Actionscript 中的代理对象以及其他语言中的类似事物不同,这在 Javascript 中并不容易做到。
如果这就是您想要的功能,那么您拥有的解决方案大约是您可以做的最简单的解决方案。您还可以创建一个.get(whatever)
返回实际[whatever]
内容的函数,但具体返回您想要的类型。你.set(whatever,value)
也可以做一个。但是,它不会阻止代码在 using 中推入东西[]
。
一方面,过度依赖 IDE 来为您执行此操作并不是一个好主意,但尝试更好地强类型化本身并不是一个坏主意。
更新:
要回答你的其他问题...首先,为了轻松测试简单的 JS 内容,最好使用命令行版本:
http://blog.thefrontside.net/javascript/learning-javascript-from-the-command-line
https://developer.mozilla.org/en/SpiderMonkey_Build_Documentation
现在,我也不建议您这样做只是为了破解 IDE,而只是为了展示“一种方法”来做到这一点:
# js
js> function FooDataClass(){ this.data = "argh!"; }
js> function FooClass(){ this.get = GetStuff; this.put = PutStuff; this.stuff = new FooDataClass(); }
js> function PutStuff(name,stuff){ this[name]= this.stuff = stuff; }
js> function GetStuff(name){ return this.stuff = this[name]; }
js> f = new FooClass()
[object Object]
js> f.put('bar', new FooDataClass())
js> f.get('bar')
[object Object]
js> f.get('bar').data
argh!
js>
Run Code Online (Sandbox Code Playgroud)
这可能会为您伪造您的 IDE。