-1

Hi I'm learning now JS Classes now and have one question, that can't understand:

var o = new F(4)
function F(temp){var a=22; this.temp = temp} 
alert(o.temp); // print 4 
alert(o.a); // print undefined

From point of OOP: "F" is class/constructor, "o" is object, "temp" is field of object, so what is variable "a" and how to get it?

Simcha
  • 3,300
  • 7
  • 29
  • 42

3 Answers3

1

o.a cannot be accessed, as your a is within the closure of F's constructor.

See this article: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions_and_function_scope

simonzack
  • 19,729
  • 13
  • 73
  • 118
1

When you above a property with the keyword var, this element is only present in his parent scope.

So, in your example, a is a private member of the F class.

For example:

'use strict';

;(function() { // private function

 var a = "toto";
 alert (a); // display "toto"

})(); // autocalled

alert (a); // undefined

Howether:

'use strict';

var a = "toto";

;(function() {
 alert (a); // display toto
}();

;(function() {
 alert (a); // display toto
}();

In this example, a is global to the current executed script and could be called everywhere in the code.

Paul Rad
  • 4,820
  • 1
  • 22
  • 23
1

As a side note: JavaScript doesn't really have 'classes' in the same way that other languages do. It's called either a prototypal or prototypical language.

On to the answer

You can't access a because it's not a member of o. If you wanted to access it by saying o.a, then in the constructor function you'd have to have written this.a = //whatever.

Constructors are just functions like any other function. The only thing that makes them a constructor is the way that the new keyword makes the function look for a prototype of the same name, making that function be its 'constructor' and setting the correct context. With that being said, any local variable you declare in the function scope will always be local to that function, regardless of whether or not that function is masquerading as a constructor at that specific point in time.

Josh Beam
  • 19,292
  • 3
  • 45
  • 68