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()?
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.
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
}
}
Your "set" function is missing a reference to this
:
this.a = 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With