javascript - 是否可以在javascript中调用私有(private)函数内部的实例变量?

标签 javascript

我有一个在 javascript 中定义的函数,它充当一个类。在其中,我定义了几个公共(public)方法,但是有一个私有(private)方法,我需要访问其中的一个公共(public)方法。

function myClass(){ 
   this.myPublicMethod = function(a,b){
       var i = a*b;
       return i;
   }

   function myPrivateMethod(){
        var n = this.myPublicMethod(2,3);
   }
}

这行不通。有没有办法在 myPrivateMethod 中访问 myPublicMethod?

最佳答案

当使用 Function.prototype.call 调用您的私有(private)方法时,您只需指定 this 的值即可。

myPrivateMethod.call(this);

例如

function myClass(){ 
   this.myPublicMethod = function(a,b){
       var i = a*b;
       return i;
   }

   function myPrivateMethod(){
        var n = this.myPublicMethod(2,3);
   }

   //calling private method in the *scope* of *this*.
   myPrivateMethod.call(this);
}

请注意,拥有真正的私有(private)成员(不是函数)是以无法利用原型(prototype)为代价的。出于这个原因,我更愿意依靠命名约定或文档来识别私有(private)成员,而不是强制执行真正的隐私。这仅适用于非单例对象。

下面的例子演示了上面所说的内容。

//Constructors starts by an upper-case letter by convention
var MyClass = (function () {

    function MyClass(x) {
        this._x = x; //private by convention
    }

    /*We can enforce true privacy for methods since they can be shared
    among all instances. However note that you could also use the same _convention
    and put it on the prototype. Remember that private members can only be 
    tested through a public method and that it cannot be overriden.*/
    function myPrivateMethod() {
        this.myPublicMethod1();
    }

    MyClass.prototype = {
        constructor: MyClass,
        myPublicMethod1: function () {
            //do something with this._x
        },
        myPublicMethod2: function () {
            /*Call the private method by specifying the *this* value.
            If we do not, *this* will be the *global object* when it will execute.*/
            myPrivateMethod.call(this);            
        }
    };

    return MyClass;

})();

关于javascript - 是否可以在javascript中调用私有(private)函数内部的实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19236898/

相关文章:

javascript - Webpack延迟加载Leaflet-Geoman

javascript - 检测悬空 promise 的静态/动态方法

javascript - 需要迷你表单将跟踪号码附加到 URL

JavaScript ondblclick 不工作

javascript - JavaScript 中是否有等效的 Task.Run ?

输入文本上的 Javascript 文本输入将格式更改为小数点后两位

javascript - 如何使用javascript动态添加videojs播放器?

javascript - 如何在 Node js Controller 文件中引用 Elastic Search JavaScript 客户端库

多个文本框的 Javascript 电子邮件验证

javascript - firefox:使用文件协议(protocol)下载javascript文件?