When I used a new variable something.something or this.something, my code worked when I omitted the var keyword:
开发者_StackOverflowthis.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 .
is not a valid character for an identifier.
It thinks you want the variable name to actually be this.something
, which isn't valid.
When testing the two versions, I get slightly different errors.
The one with this.something
tells me:
SyntaxError: Unexpected token this
The one with something.something
tells me:
SyntaxError: Unexpected token .
Same error, but the invalid token in the first is the keyword this
.
You can't declare a this
field (member field), or a field of another object. 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. And as Patrick said, a variable name can not contain a period.
var
is the syntax for declaring a variable. In Javascript simply by assigning a value to a property it will attach the property to the object.
精彩评论