需要帮助获取 JavaScript 中的变量
有人可以帮助我了解 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)。
如何根据同一命名空间内的另一个变量来声明一个变量?
Can someone please help me understand the scoop of JavaScript variables, and how to reach them?
Imagine the following...
// Namespace declaration
var p = {};
p.result = {
searchForm: $('#search-form'),
searchAction: this.searchForm.attr('action'),
anotherSection: {
hello: 'Hello ',
world: this.hello + 'world!'
}
}
This won't work, and it gives the error saying this.searchForm
is undefined. The same error appears in anotherSection
as well (ofc).
How can I declare a variable in terms of another variable inside the same namespace?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
this
关键字绑定到函数上下文,您不能在这样的对象文字中使用它。你可以将函数设置为“getters”:
The
this
keyword is bound to the function-context, you can't use it in object literals like that.You could, make functions as "getters":
在构建对象时无法引用它。
您需要编写以下内容:
There is no way to refer to an object literal as you're building it.
You need to write the following:
您无法访问对象本身文字中的属性 - 它们还不存在。
You can't access the properties of an object inside its own literal — they don't exist yet.
this 是一个对象,因此当您使用 this.searchForm 时,您正在访问 this 对象的属性。您只想访问一个变量,因此可以使用searchForm。
this is an object, so when you use this.searchForm, you are accessing a property of the this object. You just want to access a variable, so you can just use searchForm.