我有一个在 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/