Implementing private instance variables in Javascript

后端 未结 4 1000
夕颜
夕颜 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:35

    A slight modification to the code using this will work. The correct instance of Printer.prototype.print was not being instantiated for the a object.

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

提交回复
热议问题