Reputation: 6291
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()?
Upvotes: 5
Views: 168
Reputation: 96810
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);
Upvotes: 0
Reputation: 122936
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
Upvotes: 1
Reputation: 58444
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
}
}
Upvotes: 2
Reputation: 490333
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).
Upvotes: 7