-1

Would like to know what is the difference between variable test1 and test2 in the following code.

function myClass(){
var test1 = 'abc';
this.test2 = 'def';

this.Method1 = function(){
    someObj(this.success);
}

this.success = function(){
    console.log(test1); //able to output value
    console.log(this.test2); //unable to get the output
            console.log(test2); //unable to get the output
}
}

Edit: to make more precise, I was trying to access to the variable from an inner function. I couldn't access to the test2 variable, but able to extract the value from test1.

WenHao
  • 1,183
  • 1
  • 15
  • 46
  • *"...what is the difference between variable test1 and test2..."* Well, for a start, `test2` isn't a variable. :-) (See thefourtheye's answer for details...) – T.J. Crowder May 18 '14 at 08:52
  • For difference between variables and properties, have a look at [Javascript: Do I need to put this.var for every variable in an object?](http://stackoverflow.com/q/13418669/1048572) – Bergi May 18 '14 at 08:59

2 Answers2

4
  1. test1 is a variable which is local to the myClass function. It cannot be accessed outside.

  2. test2 is a property of the current object on which myClass is invoked.

Based on the fact that function name has Class in it, I assume that it is a constructor function. So, test2 will be set on the newly constructed object.

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0

Functions and function scope (MDN)

It's all about scope. There's a great example and explanation here: What is the scope of variables in JavaScript?

JavaScript really only has 2 types, functional and global.

this.test2 in this case is the same as window.test2.

The this keyword does not refer to the currently executing function, so you must refer to Function objects by name, even within the function body.

var test1 will only be defined within your function myClass

Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.

Community
  • 1
  • 1
Chase
  • 29,019
  • 1
  • 49
  • 48