Creating simple constructor in Javascript -


i trying write constructor when increment called outputs this:

var increment = new increment(); alert(increment); // 1 alert(increment); // 2 alert(increment + increment); // 7 

i trying go way:

var increment = 0; function increment(increment){     increment += 1; }; 

but alerts outputs [object object].

any idea?

edit: apparently not allowed touch existing code, cuestion of exercise is: «create constructor instances return incremented number»

ususally, need method incrementing value , need call it.

function increment(value) {      this.value = value || 0;      this.inc = function () { return ++this.value; };  }    var incrementor = new increment;    console.log(incrementor.inc()); // 1  console.log(incrementor.inc()); // 2  console.log(incrementor.inc() + incrementor.inc()); // 7

but return object closure on value instead of implicid this object , implement tostring function getting primitive value.

this solution not advisable, works educational use. (it not work console.log here, because need expecting environment primitive value.)

function increment(value) {      value = value || 0;      return {          tostring: function () { return ++value; }      };  }    var increment = new increment;    alert(increment); // 1  alert(increment); // 2  alert(increment + increment); // 7


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

reflection - How to access the object-members of an object declaration in kotlin -

php - Doctrine Query Builder Error on Join: [Syntax Error] line 0, col 87: Error: Expected Literal, got 'JOIN' -