Accessing private member variables from prototype-defined functions

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

    You need to change 3 things in your code:

    1. Replace var privateField = "hello" with this.privateField = "hello".
    2. In the prototype replace privateField with this.privateField.
    3. In the non-prototype also replace privateField with this.privateField.

    The final code would be the following:

    TestClass = function(){
        this.privateField = "hello";
        this.nonProtoHello = function(){alert(this.privateField)};
    }
    
    TestClass.prototype.prototypeHello = function(){alert(this.privateField)};
    
    var t = new TestClass();
    
    t.prototypeHello()
    

提交回复
热议问题