How to Create static variable in JavaScript?
static variable concept is present in class based languages like Java or C#. It is a variable which belongs to the class and not to object(instance) of the class. Below sample code is using static variable concept in JavaScript.
Here, For each object creation the id value will be incremented by one.
class test{
constructor(){
this.id = this.createId();
}
createId(){
this.__proto__.id = this.__proto__.id + 1;
return this.__proto__.id;
}
}
test.prototype.id = 0;
const test1 = new test();
console.log(test1); //{ id: 1 }
const test2 = new test();
console.log(test2); //{ id: 2 }
const test3 = new test();
console.log(test3);//{ id: 3 }
Comments
Post a Comment