javascript封装 - 任何访问私有成员给定实例的方法?

And*_* B. 0 javascript

在给定实例变量的情况下,是否可以在javascript中访问私有成员?例如,

function class Foo() {
   var x=12;
   // some other stuff
}
F = new Foo();
// how to get/set F.x?
Run Code Online (Sandbox Code Playgroud)

更新:作为一种扭曲,假设该类具有特权方法.是否有可能劫持这种特权方法来访问私有成员?

function class Foo() {
   var x=12, y=0;
   this.bar = function(){ y=y+1; }
}
F = new Foo();
// can I modify Foo.bar to access F.x?
Run Code Online (Sandbox Code Playgroud)

Šim*_*das 5

您需要一个特权方法来获取/设置值x:

function Foo() {
    var x = 12;
    this.getX = function() { return x; };
    this.setX = function(v) { x = v; };
}

var f = new Foo(),
    g = new Foo();

f.getX(); // returns 12
g.getX(); // returns 12

f.setX(24);

f.getX(); // returns 12
g.getX(); // returns 24

g.setX(24); 

f.getX(); // returns 24
g.getX(); // returns 24
Run Code Online (Sandbox Code Playgroud)

现场演示: http ://jsfiddle.net/simevidas/j7VtF/