私有对象属性

时间:2012-10-20 07:23:57

标签: javascript object prototype requirejs private

我有一个RequireJs模块,它实例化另一个模块并代理它的一些方法。我现在想隐藏模块实例本身,只允许通过代理方法进行访问。

define(['mediator'], function(Mediator) {

  var Proxy;

  Proxy = function(prefix) {
    this.prefix = prefix;
    this.mediator = new Mediator();
  };

  Proxy.prototype.on = function(event, callback, context) {
    this.mediator.subscribe(this.prefix + event, callback, context || this);
  };

  Proxy.prototype.off = function(event, callback, context) {
    this.mediator.unsubscribe(this.prefix + event, callback, context || this);
  };

  Proxy.prototype.trigger = function() {
    arguments[0] = this.prefix + arguments[0];
    this.mediator.trigger.apply(this.mediator, arguments);
  };

  return Proxy;

});

require(['proxy'], function(Proxy) {

  var proxy = new Proxy('sample:');

  // this access is secured and bound to the prefix
  // I cannot mess up with other events which do not belong to me
  proxy.on('log', function(message) { console.log(message); });
  proxy.trigger('log', 'hi hello');

  // unfortunately there still would be a hack to leave my event scope
  proxy.mediator.trigger('outerscope:test', 'blabla');

});

如您所见,可以访问代理原型的内部使用的中介对象并搞砸它......

我现在想以某种方式隐藏中介实例,但不知道在哪里。 我可以将它存储在requirejs模块回调中的一些常规变量中,但这对requirejs不起作用,并且可能导致重叠。

那我该怎么办?

更新

define(['mediator'], function(Mediator) {

  var Proxy;

  var mediator = new Mediator();

  Proxy = function(prefix) {
    this.prefix = prefix;
  };

  Proxy.prototype.on = function(event, callback, context) {
    mediator.subscribe(this.prefix + event, callback, context || this);
  };

  Proxy.prototype.off = function(event, callback, context) {
    mediator.unsubscribe(this.prefix + event, callback, context || this);
  };

  Proxy.prototype.trigger = function() {
    arguments[0] = this.prefix + arguments[0];
    mediator.trigger.apply(this.mediator, arguments);
  };

  return Proxy;

});

require(['proxy'], function(Proxy) {

  var proxy = new Proxy('sample:');
  proxy.on('log', function(message) { console.log(message); });

});

1 个答案:

答案 0 :(得分:2)

这是在Javascript中封闭变量的典型示例。您需要的是将中介实例定义为与Proxy在同一范围内的局部变量。这将允许Proxy对象通过闭包访问Mediator,但会将Mediator与define-callback之外的代码隔离开来。像这样:

define(['mediator'], function(Mediator) {

    // Make mediator local scope variable
    var mediator = new Mediator(),

    Proxy = function(prefix) {
        this.prefix = prefix;
    };

    Proxy.prototype.on = function(event, callback, context) {
        mediator.subscribe(this.prefix + event, callback, context || this);
    };

    // ... rest of the code

    return Proxy;

});