2

一段时间以来,我想知道是否有更快的方法在 javascript 中实例化对象链。

假设我们例如有以下“对象链”

window.myobject1.myobject2.myobject3 = {}

这当然行不通..因为object1和object2没有被实例化..但是..要让它工作..我必须做类似的事情:

window.myobject1 = {}
window.myobject1.myobject2 = {}
window.myobject1.myobject2.myobject3 = {}

这只是看起来很愚蠢..在更现实的情况下..假设我们有

window.server.responses.currentuser.id

其中服务器、响应和当前用户只是充当“命名空间”/空实体。有什么方法可以告诉 javascript 将整个链实例化为对象?...所以我不需要实例化链的每个部分在新线上?

这可能是一个不好的例子,但我想你明白了.. 例如我可能还有:

window.server.responses.currentuser.id
window.server.responses.theotherusers.personone.id
window.server.responses.labels.personname

ETC..

提前致谢!

4

1 回答 1

-1

I've answered this question before but can't seem to find it so can't mark this as duplicate (hehe). Anyway, you can basically do it with a function:

function deep_set (obj,path,value) {
    var name = path.shift();
    if (path.length) {
        if (typeof obj[name] == undefined) {
            obj[name] = {};
        }
        if (typeof obj[name] == 'string' || typeof obj[name] == 'number') {
            throw new Error('attempted to access string or number as object');
        }
        deep_set(obj[name],path,value);
    }
    else {
        obj[name] = value;    
    }
}

So you can now do:

deep_set(window,['server','responses','currentuser','id'],3);

without having to manually test typeof == undefined at each step.

With a little change you can have the API look any way you want:

window.deep_set(['server','responses','currentuser','id'],3);
// or
deep_set(window,'server','responses','currentuser','id',3);
// or
deep_set(window,'server.responses.currentuser.id',3);
于 2013-10-29T15:10:01.867 回答