1

I'm new to JS so noob question:

I see functions which define vars inside them:

 function functionName(){
     this.something = "";
 };

If I understand correctly, something is a local variable? Why is it being defined as this.something = '' as opposed to var something = ''? Is there any difference, and if so what is it?

Allen S
  • 3,471
  • 4
  • 34
  • 46
  • this relates to the scope of the variable, http://javascriptweblog.wordpress.com/2010/08/30/understanding-javascripts-this/ – Neil Jul 30 '13 at 11:47
  • You may want to check out this question and its accepted answer: http://stackoverflow.com/questions/500431/javascript-variable-scope?rq=1 tl;dr: use of `var` makes something a variable scoped to that context; omitting the `var` implicitly marks the variable as global; using `this` makes it a property of the execution context (the `this` object) – founddrama Jul 30 '13 at 11:50
  • Check if this helps - http://stackoverflow.com/questions/11285975/difference-between-var-and-this-in-javascript-functions – Harry Jul 30 '13 at 11:50

2 Answers2

4

It sets the attribute something of this. What this refers to depends on how functionName is invoked, but typically it's an object created with new:

var foo = new functionName();
console.log(foo.something);

If you'd use var something inside the function, the variable would be inaccessible from outside, so you couldn't do foo.something in the above example.

deceze
  • 510,633
  • 85
  • 743
  • 889
1
var someThing 

is a local variable - meaning it exists within the scope of the current block

this.someThing

is an instance variable - meaning it belongs to the object and is visible in all methods of that object.