Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class and scope in Javascript

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()?

like image 583
Jinu Joseph Daniel Avatar asked Jul 17 '11 13:07

Jinu Joseph Daniel


4 Answers

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.

like image 174
alex Avatar answered Oct 05 '22 23:10

alex


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
    }
}
like image 22
tereško Avatar answered Oct 05 '22 23:10

tereško


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

   this.a = 1;
like image 45
Pointy Avatar answered Oct 05 '22 22:10

Pointy


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

like image 36
KooiInc Avatar answered Oct 05 '22 22:10

KooiInc