简体   繁体   English

JS对象文字范围和引用

[英]JS object literal scope and referencing

I use an object literal to collect various DOM elements I add dynamically because I want to be able to reference them by variable (code below is simplified, there would be much more, like events and so on): 我使用对象文字来收集动态添加的各种DOM元素,因为我希望能够通过变量引用它们(下面的代码经过简化,会有更多东西,例如事件等):

ui = {
  header : $('<div id="header"></div>').appendTo('body').css('color','#009'),
  footer : $('<div id="footer"></div>').appendTo('body').css('color','#990')
}

Now I wish I could just add other objects to this, but it will throw an error: 现在,我希望可以向此对象添加其他对象,但是它将引发错误:

ui = {
  header : $('<div id="header"></div>').appendTo('body').css('color','#009'),
  footer : $('<div id="footer"></div>').appendTo('body').css('color','#990'),
  headerSpecial : $('<span>some header</span>').appendTo(ui.header) // this line will cause an error "ui is not defined"
}

I suppose this is because until the ui object is closed, I can't reference anything inside yet. 我想这是因为在ui对象关闭之前,我还不能引用其中的任何内容。 SO I would have to separate out these things into separate objects. 所以我将不得不将这些东西分离成单独的对象。 But is there some way I can do it all in a single object? 但是,有什么方法可以在单个对象中完成所有操作? Should I wrap some stuff in anonymous functions and then call them? 我应该在匿名函数中包装一些东西然后调用它们吗?

It is no problem to use one and the same object to hold the references, but you cannot use self references in one and the same literal expression. 使用一个相同的对象来保存引用是没有问题的,但是您不能在一个相同的文字表达式中使用自我引用。 Do it in two steps: 分两个步骤进行:

// create the object
ui = {
  header : $('<div id="header"></div>').appendTo('body').css('color','#009'),
  footer : $('<div id="footer"></div>').appendTo('body').css('color','#990')
}

// add a new property to the object
ui.headerSpecial = $('<span>some header</span>').appendTo(ui.header);

Rather than using an object literal, why not instantiate an anonymous function? 为什么不实例化一个匿名函数而不是使用对象文字?

ui = new function () {
    this.header = $('<div id="header"></div>').appendTo('body').css('color','#009');
    this.footer = $('<div id="footer"></div>').appendTo('body').css('color','#990');
    this.headerSpecial = $('<span>some header</span>').appendTo(this.header);
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM