【问题标题】:Private object properties私有对象属性
【发布时间】:2012-10-20 07:23:57
【问题描述】:

我有一个 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); });

});

【问题讨论】:

  • this would not work good with requirejs and could cause overlapping 是什么意思?这是封装 Mediator 实例的好方法。它可用于代理,但不可用于外部。正是您需要的。
  • @dfsq 你能写一个答案让我标记吗?

标签: javascript object prototype requirejs private


【解决方案1】:

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

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;

});

【讨论】:

    猜你喜欢
    • 2015-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-07
    • 2019-11-20
    相关资源
    最近更新 更多