Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems with basic prototyping in Javascript

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.... :(

like image 413
Harshit Laddha Avatar asked Dec 11 '22 12:12

Harshit Laddha


1 Answers

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;
}

Example Fiddle

like image 69
Sirko Avatar answered Dec 27 '22 13:12

Sirko