Accessing private member variables from prototype-defined functions

前端 未结 25 1238
孤城傲影
孤城傲影 2020-11-22 14:48

Is there any way to make “private” variables (those defined in the constructor), available to prototype-defined methods?

TestClass = function(){
    var priv         


        
25条回答
  •  [愿得一人]
    2020-11-22 15:42

    Can't you put the variables in a higher scope?

    (function () {
        var privateVariable = true;
    
        var MyClass = function () {
            if (privateVariable) console.log('readable from private scope!');
        };
    
        MyClass.prototype.publicMethod = function () {
            if (privateVariable) console.log('readable from public scope!');
        };
    }))();
    

提交回复
热议问题