4

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

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

You posted the same solution 7 seconds before me :) +1
6

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

thanks a lot i completely forgot that , it works thank you very much
@user1860959 If an answer solved your problem, mark it as such by clicking the checkmark right next to it (upper left).
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.