需要帮助获取JavaScript中的变量吗
有人能帮助我了解JavaScript变量的独家新闻,以及如何访问它们吗 想象一下下面需要帮助获取JavaScript中的变量吗,javascript,variables,namespaces,declaration,Javascript,Variables,Namespaces,Declaration,有人能帮助我了解JavaScript变量的独家新闻,以及如何访问它们吗 想象一下下面 // Namespace declaration var p = {}; p.result = { searchForm: $('#search-form'), searchAction: this.searchForm.attr('action'), anotherSection: { hello: 'Hello ', world: this.he
// Namespace declaration
var p = {};
p.result = {
searchForm: $('#search-form'),
searchAction: this.searchForm.attr('action'),
anotherSection: {
hello: 'Hello ',
world: this.hello + 'world!'
}
}
这将不起作用,并且会出现错误,提示This.searchForm
未定义。同样的错误也出现在另一节中(ofc)
如何根据同一命名空间中的另一个变量声明变量?this关键字绑定到函数上下文,不能在那样的对象文本中使用它 您可以将函数设置为“getter”:
此是一个对象,因此当您使用this.searchForm时,您正在访问此对象的属性。您只想访问一个变量,所以您可以使用searchForm在构建对象文字时无法引用它 您需要编写以下内容:
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!';
您不能在对象本身的文本中访问对象的属性-它们还不存在 +1谢谢,但这次我会选择CMS提供的解决方案。+1用于编辑和编码示例。我认为这看起来是一个很好的解决方案:)您可以使用
this.getWorld=this.hello+'world!'对其进行优化;返回此.getWorld
,以便它仅在第一次被调用时连接字符串。
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!';