需要帮助在JavaScript中获取变量

时间:2009-12-27 15:30:24

标签: javascript variables namespaces declaration

有人可以帮我理解JavaScript变量的独家新闻,以及如何实现这些变量吗?

想象一下......

// Namespace declaration
var p = {};

p.result = {

    searchForm: $('#search-form'),
    searchAction: this.searchForm.attr('action'),

    anotherSection: {
        hello: 'Hello ',
        world: this.hello + 'world!'
    }

}

这不起作用,它会给出错误,指出this.searchForm未定义。同样的错误也出现在anotherSection(ofc)中。

如何根据同一名称空间内的另一个变量声明变量?

4 个答案:

答案 0 :(得分:3)

this关键字绑定到 function-context ,您不能在像这样的对象文字中使用它。

你可以将函数设为“getters”:

var p = {};
p.result = {
  searchForm: $('#search-form'),
  getSearchAction: function () {
    return this.searchForm.attr('action');
  },
  anotherSection: {
    hello: 'Hello ',
    getWorld: function () {
      return this.hello + 'world!';
    }
  }
};

答案 1 :(得分:3)

在构建对象文字时无法引用对象文字。

您需要撰写以下内容:

p.result = {
    searchForm: $('#search-form'),
    anotherSection: {
        hello: 'Hello '
    }
}

p.result.searchAction = p.result.searchForm.attr('action');
p.result.anotherSection.world = p.result.anotherSection.hello + 'world!';

答案 2 :(得分:1)

您无法访问其自身文字内的对象属性 - 它们尚不存在。

答案 3 :(得分:0)

是一个对象,因此当您使用 this.searchForm 时,您正在访问对象的属性。您只想访问变量,因此您只需使用 searchForm

相关问题