Javascript base prototype issues

I am new to javascript and I started with something where I am stuck in some basics, the thing is, I try to create a prototype for an object and then reference the created objects in an array and then join their methods, but I I'm mistaken somewhere, can someone help me with this, what I'm 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 work ... :(

+4
source share
3 answers

You do not assign a property to the Obj object, but simply have a local variable inside the constructor. Change it like this:

 function Obj(n){ this.name = n; } 

Script example

+6
source

Your problem with the constructor, you assign a parameter to a local variable not a field variable, change it like this:

 function Obj(n){ this.name=n; } 

Hope this helps

+6
source

Use this:

  function Obj(n){ this.name=n; } 

CAUSE:

The difference between var name=n; and this.name=n;

var name = n;

A variable declared with var is a local constructor function. It will go beyond the constructor call if it is used by some method inside the object

this.name = n;

this is a property of the object, and it will be preserved as long as the object does, regardless of whether it is used or not.

Example: this in javascript

+1
source

Source: https://habr.com/ru/post/1494065/


All Articles