javascriptproxy-pattern

Method delegation to the parent in case of implementing proxies in JavaScript


In an example from Node.js Design patterns

  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);
   }

What is the need for the method delegation i.e. to redefine the Proxy.prototype.goodbye method again when the method from original Object will be automatically be called as the prototype chain has been set i.e. Proxy.prototype = Object.create(proto). Thanks in advance.


Solution

  • The newly instantiated Proxy does not inherit from the subject - the properties directly on subject's are only available on the proxy's subject property. Only the prototype methods of the subject are available immediately on the Proxy object itself. So, in the case that goodbye is a property directly on the instantiated object, you wouldn't be able to access it directly were the Proxy.prototype.goodbye = ... line not there:

    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();

    Those methods are available through the instantiated proxy's .subject, but not through the proxy itself, unless you explicitly assign to Proxy.prototype.goodbye as in the original code.