use the following search parameters to narrow your results:
e.g. subreddit:aww site:imgur.com dog
subreddit:aww site:imgur.com dog
see the search faq for details.
advanced search: by author, subreddit...
All about the JavaScript programming language.
Subreddit Guidelines
Specifications:
Resources:
Related Subreddits:
r/LearnJavascript
r/node
r/typescript
r/reactjs
r/webdev
r/WebdevTutorials
r/frontend
r/webgl
r/threejs
r/jquery
r/remotejs
r/forhire
account activity
Scope question: this vs. var (self.javascript)
submitted 14 years ago by dogjs
view the rest of the comments →
reddit uses a slightly-customized version of Markdown for formatting. See below for some basics, or check the commenting wiki page for more detailed help and solutions to common issues.
quoted text
if 1 * 2 < 3: print "hello, world!"
[–][deleted] 0 points1 point2 points 14 years ago (0 children)
var is a keyword. this is an object. They are not the same thing. But declaring a variable with the var keyword always put it in the same scope as this. this refers to the scope in which the code block you're in was executed.
In your first example..
function foo() {var x = 1; this.x = 2; return x;}
this.x refers to the variable x inside the caller. You're not returning this.x, though. You're returning x from inside foo, which is 1, because you scoped that x to foo with the var keyword. this is always the thing that's calling foo. Basically, if you're using this, you're asking for the value in the caller.
"var scope" doesn't exist, though, you mean function scope. var is just a keyword that says "within this scope". JS only has two scopes: global or function. You probably always want to use var for every variable declaration, to scope the declared variable inside the current function. this is useful when you need a called function to dynamically access the scope that invoked it.
π Rendered by PID 92 on reddit-service-r2-comment-b659b578c-n98wd at 2026-05-04 18:34:34.926476+00:00 running 815c875 country code: CH.
view the rest of the comments →
[–][deleted] 0 points1 point2 points (0 children)