Static variables in JavaScript

后端 未结 30 2232
别那么骄傲
别那么骄傲 2020-11-22 01:55

How can I create static variables in Javascript?

30条回答
  •  名媛妹妹
    2020-11-22 02:18

    If you want to use prototype then there is a way

    var p = function Person() {
        this.x = 10;
        this.y = 20;
    }
    p.prototype.counter = 0;
    var person1 = new p();
    person1.prototype = p.prototype;
    console.log(person1.counter);
    person1.prototype.counter++;
    var person2 = new p();
    person2.prototype = p.prototype;
    console.log(person2.counter);
    console.log(person1.counter);
    

    Doing this you will be able to access the counter variable from any instance and any change in the property will be immediately reflected!!

提交回复
热议问题