i am kinda new to javascript and i started off on something where i am stuck with some basics, the thing is i am trying to create an prototype for an object and then the references of created objects in an array and then accesing their methods but i am wrong somewhere can anyone help me with this, what i am doing is shown here :-
function Obj(n){
var name=n;
}
Obj.prototype.disp = function(){
alert(this.name);
};
var l1=new Obj("one");
var l2=new Obj("two");
var lessons=[l1,l2];
//lessons[0].disp();
//alert(lessons[0].name);
but none of these methods seem to work out.... :(
3 Answers 3
You not assigning a property of the Obj object, but just have a local variable inside the constructor. Change like this:
function Obj(n){
this.name = n;
}
1 Comment
Your problem is with the constructor, you are assigning the parameter to a local variable not to a field variable, change it like:
function Obj(n){
this.name=n;
}
Hope this helps
2 Comments
Use this:
function Obj(n){
this.name=n;
}
REASON:
Difference between var name=n; and this.name=n;
var name=n;
The variable declared with var is local to the constructor function. It will only survive beyond the constructor call if it's used in some method inside the object
this.name=n;
this is property of the object, and it will survive as long as the object does, irrespective of whether it's used or not.
Example:this in javascript