简体   繁体   English

为什么全局和this.something变量没有被删除?

[英]Why are global and this.something variables not decleared?

When I used a new variable something.something or this.something, my code worked when I omitted the var keyword: 当我使用一个变量some​​thing.something或this.something时,我的代码在省略var关键字时起作用:

this.something = 1;
something.something = 1;

but when I write 但是当我写作

var this.something = 1;
var something.something = 1;

it doesn't work. 它不起作用。

Why? 为什么?

I suppose because var expects a valid identifier, and . 我想因为var需要一个有效的标识符,并且. is not a valid character for an identifier. 不是标识符的有效字符。

It thinks you want the variable name to actually be this.something , which isn't valid. 它认为您希望变量名实际上是this.something ,这是无效的。


When testing the two versions, I get slightly different errors. 在测试这两个版本时,我会遇到稍微不同的错误。

The one with this.something tells me: 有这个this.something告诉我:

SyntaxError: Unexpected token this SyntaxError:意外的令牌

The one with something.something tells me: 带有something.something那个something.something告诉我:

SyntaxError: Unexpected token . SyntaxError:意外的令牌。

Same error, but the invalid token in the first is the keyword this . 同样的错误,但第一个中的无效令牌是关键字this

You can't declare a this field (member field), or a field of another object. 您不能声明this字段(成员字段)或另一个对象的字段。 It's simply not valid syntax. 这根本就不是有效的语法。

You use var to declare local variables, which are either function-level or (if you're not in a function) global. 您可以使用var来声明局部变量,这些变量可以是函数级的,也可以是(如果您不在函数中)全局变量。 And as Patrick said, a variable name can not contain a period. 正如帕特里克所说,变量名称不能包含句点。

var is the syntax for declaring a variable. var是声明变量的语法。 In Javascript simply by assigning a value to a property it will attach the property to the object. 在Javascript中,只需为属性赋值,它就会将属性附加到对象。

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

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