Implementing private instance variables in Javascript

后端 未结 4 1002
夕颜
夕颜 2020-12-05 03:07

I don\'t know how I\'ve missed this for so long. I\'ve been presuming private instance variables to work like this, but they don\'t. They\'re private (as in non-global), cer

4条回答
  •  一向
    一向 (楼主)
    2020-12-05 03:45

    You're doing some wonky stuff with that closure. _word needs to be declared in the Printer function, not lost in anonymous-closure land:

    function Printer(word) {
        var _word = word;
    
        this.print = function () {
            console.log(_word);
        }
    }
    
    var a = new Printer("Alex");
    var b = new Printer("Bob");
    
    a.print(); //Prints Alex
    b.print(); //Prints Bob
    

    This keeps _word private, at the expense of creating a new print function on every Printer instance. To cut this cost, you expose _word and use a single print function on the prototype:

    function Printer(word) {
        this._word = word;
    }
    
    Printer.prototype.print = function () {
        console.log(this._word);
    }
    
    var a = new Printer("Alex");
    var b = new Printer("Bob");
    
    a.print(); //Prints Alex
    b.print(); //Prints Bob
    

    Does it really matter that _word is exposed? Personally, I don't think so, especially given the _ prefix.

提交回复
热议问题