5

I wrote the following code in Javascript.

function main()
{
    this.a ;
    this.set = function()
    {
        a = 1;
    }
}

var l = new main();

alert("Initial value of a is "+ l.a );
l.set();
alert("after calling set() value of a is   "+ l.a );

In both cases i got value of a as undefined .Why a is undefined even after I called set()?

Sandro Munda
  • 39,921
  • 24
  • 98
  • 123
Jinu Joseph Daniel
  • 5,864
  • 15
  • 60
  • 90

5 Answers5

7

You need to refer to a with this.a.

Otherwise, you are referring to a local variable a (had you used var, omitting it has made an a property on the window object, essentially a global) and not the object's property a (this will be bound to the newly created object).

jsFiddle.

alex
  • 479,566
  • 201
  • 878
  • 984
2

Your "set" function is missing a reference to this:

   this.a = 1;
Pointy
  • 405,095
  • 59
  • 585
  • 614
2

to javascript this:

function main()
{
    this.a ;
    this.set = function()
    {
        a = 1;
    }
}

will looks like

function main();

{ // starts unattached object literal
    this.a ;
    this.set = function();

    { // starts another unattached object literal 
        a = 1; // sets value to   window.a
    }
}
tereško
  • 58,060
  • 25
  • 98
  • 150
1

In addition to the previous answers: there are no classes in Javascript, only objects. You can construct class-like things, but the javascript inheritance model is prototypal. In your code, main is a constructor function, from which you can derive instances.

Many people are still trying to force javascript into all kinds of classic OOP patterns. It's all perfectly possible, but it's crippling the language. Take some time to watch this series of lectures

KooiInc
  • 119,216
  • 31
  • 141
  • 177
0

You can't declare a property of an object undefined as you've done it. And you referenced the property a incorrectly in the case method. Here is the correction:

function main() {
    this.a = null;
    this.set = function() {
        this.a = 1;
    }
}

var l = new main();

alert("Initial value of a is " + l.a);
l.set();
alert("after calling set() value of a is   " + l.a);
David G
  • 94,763
  • 41
  • 167
  • 253