0

Node.js 设计模式的示例中

  function createProxy(subject) {
     var proto = Object.getPrototypeOf(subject);
     function Proxy(subject) {
       this.subject = subject;
     }
     Proxy.prototype = Object.create(proto);
     //proxied method
     Proxy.prototype.hello = function() {
       return this.subject.hello() + ' world!';
     }
     //delegated method
     Proxy.prototype.goodbye = function() {
       return this.subject.goodbye
         .apply(this.subject, arguments);
}
     return new Proxy(subject);
   }

当原型链已设置时将自动调用来自原始对象的方法时, 方法委托需要重新定义Proxy.prototype.goodbye方法,即Proxy.prototype = Object.create(proto)。提前致谢。

4

2 回答 2

2

这段代码没有任何意义。没有理由在这里涉及继承 - 正如您注意到的那样,它使一切变得混乱。

应该简化为

function createProxy(subject) {
  return {
    // proxied method
    hello() {
      return subject.hello() + ' world!';
    },
    // delegated method
    goodbye() {
      return subject.goodbye.apply(subject, arguments);
    }
  };
}

或者如果想使用原型对象来共享方法,那么

function Proxy(subject) {
  this.subject = subject;
}
// proxied method
Proxy.prototype.hello = function() {
  return this.subject.hello() + ' world!';
};
// delegated method
Proxy.prototype.goodbye = function() {
  return this.subject.goodbye.apply(this.subject, arguments);
};

function createProxy(subject) {
  return new Proxy(subject);
}

也许他们希望使用原型继承来实现所有(非覆盖)方法的隐式委托,如下所示:

function createProxy(subject) {
  var proxy = Object.create(subject);
  // proxied method
  proxy.hello = function() {
    return subject.hello() + ' world!';
  }
  // 'goodbye' and everything else on the subject is delegated
  return proxy;
}
于 2018-06-19T11:37:52.130 回答
1

新实例化Proxy的不继承subject- 直接在subject's 上的属性仅在代理的主题属性上可用。只有Proxy 对象本身的原型方法可以立即使用。subject因此,如果它是直接在实例化对象上的属性,则如果该行不存在goodbye,您将无法直接访问它:Proxy.prototype.goodbye = ...

function createProxy(subject) {
  var proto = Object.getPrototypeOf(subject);
  function Proxy(subject) {
    this.subject = subject;
  }
  Proxy.prototype = Object.create(proto);
  //proxied method
  Proxy.prototype.hello = function() {
    return this.subject.hello() + ' world!';
  }
  return new Proxy(subject);
}
const prox = createProxy({
  goodbye() {
    console.log('goodbye.')
  }
});
prox.goodbye();

这些方法可以通过实例化的代理获得.subject,但不能通过代理本身获得,除非您在原始代码中明确分配给。 Proxy.prototype.goodbye

于 2018-06-19T11:34:38.690 回答