我希望能够将一堆不同变量的地址存储在一个数组中。这使我可以按名称访问变量或在需要时遍历它们。这在JS中可能吗?
(function(ns){
ns.obj = new function(){
var foo = "foo";
var bar = "bar";
//i really want this:
//var ary = [&foo, &bar];
var ary = [foo, bar];
this.print = function() {
console.log( foo );
console.log( bar );
}
this.setFoo = function( newFoo ) {
//i really want this:
//*(ary[0]) = newFoo;
ary[0] = newFoo;
}
this.printAry = function() {
for( var i=0; i < ary.length; ++i ) {
console.log( ary[i] );
}
}
};
}(window.ns = window.ns || {}) );
ns.obj.print();
ns.obj.setFoo("newfoo!");
ns.obj.printAry();
ns.obj.print();
我看着这个:
但我希望能够ary
在作业的 LHS 上使用一个元素,我认为该示例在这种情况下不起作用。
我到底为什么要这样做?
到目前为止,很多评论(正确地)问我为什么要这样做。我正在处理一个涉及异步对象初始化机制的专有 API。基本上我创建一个对象的实例,然后将它传递给这个初始化程序以便能够实际使用它。初始化程序包括一个用于通知成功初始化的 onSuccess 处理程序的字段。我完全初始化的对象作为参数传递给这个成功处理程序,以便我可以获取对它的引用。
然后我可以自由地初始化我的下一个对象。它看起来有点像这样:
var a = new api.ApiObject();
var b = new api.ApiObject();
var c = new api.ApiObject();
var d = new api.ApiObject();
//omg this is ugly
api.initializeObject( {
objToInit: a,
onSuccess: function(args) {
a = args.obj;
api.initializeObject( {
objToInit: b,
onSuccess: function(args) {
b = args.obj;
api.initializeObject( {
objToInit: c,
onSuccess: function(args) {
c = args.obj;
api.initializeObject( {
objToInit: d,
onSuccess: function(args) {
d = args.obj;
}
} );
}
} );
}
} );
}
} );
a.doCoolStuff();
//and so on
随着我添加更多,这种深层嵌套的混乱只会变得更糟api.ApiObjects()
。那么我该怎么做才能解决这个问题呢?我无法更改 API,但也许递归函数会有所帮助:
//maybe a recursive function could make this more concise?
function doInitialize( ary ) {
api.initializeObject( {
objToInit: ary[0];
onSuccess: function(args) {
//i'd like to assign this passed in reference to my local
//reference outside this function (var a, b, etc).
//An array of pointers would be useful here.
//how else can I get this assigned out, cuz this doesn't work...
ary[0] = args.obj;
if( ary.length > 1 ) {
ary.splice( 0, 1 );
doInitialize( ary );
}
}
}
}
doInitialize( [a,b,c,d] );
//this won't work because I don't have a reference to the fully initialized object
a.doCoolStuff();
所以也许更好的问题是:是否有一个既定的模式来处理这样的异步成功链接?我想我已经看到其他公共 JS 框架(如 dojo)使用这种 onSuccess 链接......我怎样才能让它不丑?