[英]Scope of Variables declared within javascript object
I was trying to understand the scope of variables in javascript objects. 我试图了解javascript对象中变量的范围。 But the behavior that I am getting seems to be a little off the road.
但我得到的行为似乎有点不起作用。 To put it simply, if I have an object that defines a function as a variable, then the function variable is not able to access other variables of the object in which it is defines.
简单地说,如果我有一个将函数定义为变量的对象,那么函数变量就无法访问其定义的对象的其他变量。 The code below will make things clear.
下面的代码将使事情变得清晰。
<html>
<head>
<script type="text/javascript">
var someObject = {
someVariable : 5,
getVariable: function() {
return someVariable;
}
};
window.onload = function () {
alert(someObject.getVariable());
};
</script>
</head>
<body>
Hello There
</body>
</html>
The above code gives "ReferenceError: someVariable is not defined" for the someVariable in function getVariable(). 上面的代码为函数getVariable()中的someVariable提供了“ReferenceError:someVariable is not defined” 。 Would anyone like to comment on this behavior?
有人想评论这种行为吗?
Absolutely. 绝对。
The "variable" you're talking about isn't a "variable", it's a property
of an object (the object happening to be a variable). 你所谈论的“变量”不是一个“变量”,它是一个对象的
property
(该对象恰好是一个变量)。
As such, you have two options. 因此,您有两种选择。
Assuming that your object is made like this: 假设您的对象是这样的:
var obj = {
property : 42,
everything : function () { /* ... */ }
};
The two options for inside of your function body, to return the value 42 are: 函数体内部的两个选项,返回值42是:
obj.property;
OR 要么
this.property;
When you call: 你打电话时:
obj.everything();
The JS interpreter will see obj
as being equal to this
inside of the function. 该JS解释器将看到
obj
为等于this
函数的内部。
Or you reference obj
itself, directly, and access property
using either .property
dot-notation, or ["property"]
bracket-notation. 或者直接引用
obj
本身,并使用.property
dot-notation或["property"]
括号表示法访问property
。
That is not a variable, that is a property/field of an object. 这不是变量,即对象的属性/字段。
Try this.someVariable
. 试试
this.someVariable
。
Here this
is a (rather special) variable that points to the object, and the dot (or square bracket) syntax can be used to access fields of that object. this
是一个指向对象的(相当特殊的)变量,点(或方括号)语法可用于访问该对象的字段。
You can also do someObject.someVariable
in places where someObject
(another variable pointing at the object) is in scope. 您还可以在
someObject
(指向对象的另一个变量)在范围内的位置执行someObject.someVariable
。
Try this.someVariable
: 试试
this.someVariable
:
var someObject = {
someVariable: 5,
getVariable: function () {
return this.someVariable;
}
};
window.onload = function () {
alert(someObject.getVariable());
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.