javascript封装 - 任何访问私有成员给定实例的方法? [英] javascript encapsulation - any way to access a private member given instance?

查看:68
本文介绍了javascript封装 - 任何访问私有成员给定实例的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is it possible to access a private member in javascript given an instance variable? For example,

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

更新:假设该类具有特权方法。是否有可能劫持这种特权方法来访问私有成员?

Update: as a twist, suppose that the class has a privileged method. Is it possible to hijack that privileged method to access a private member?

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?


推荐答案

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

You'll need a privileged method to get/set the value of 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

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

这篇关于javascript封装 - 任何访问私有成员给定实例的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆