简体   繁体   中英

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:

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 . 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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