Accessing private member variables from prototype-defined functions

前端 未结 25 1299
孤城傲影
孤城傲影 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:30

    @Kai

    That won't work. If you do

    var t2 = new TestClass();
    

    then t2.prototypeHello will be accessing t's private section.

    @AnglesCrimes

    The sample code works fine, but it actually creates a "static" private member shared by all instances. It may not be the solution morgancodes looked for.

    So far I haven't found an easy and clean way to do this without introducing a private hash and extra cleanup functions. A private member function can be simulated to certain extent:

    (function() {
        function Foo() { ... }
        Foo.prototype.bar = function() {
           privateFoo.call(this, blah);
        };
        function privateFoo(blah) { 
            // scoped to the instance by passing this to call 
        }
    
        window.Foo = Foo;
    }());
    

提交回复
热议问题