javascript - 嵌套 ES6 代理未按预期工作

标签 javascript node.js ecmascript-6 es6-proxy

我正在开发一个 API 客户端,它允许在提供 foo 的 ID 时调用特定的 API 方法,如下所示:

apiClient.myApiMethod('myFooId', 'firstApiArg', 'nthApiArg');

为了开发人员的方便,我正在尝试实现自定义代理对象:

var myFoo = apiClient.registerFoo('myFoo', 'myFooId');
myFoo.myApiMethod('firstApiArg', 'nthApiArg');

经过一段时间的搜索,我认为 ES6 代理可能最适合这种情况,因为需要插入 fooId 作为方法调用的第一个参数以支持两种工作方式。
因此,我创建了以下代码。如果调用 Foo.myFoos 的对象属性(例如 Foo.myFoos.example),则会在 _myFooItems 中搜索它,如果存在,则返回另一个 Proxy 对象。
现在,如果在那个对象上调用方法,则会在Foo的属性中搜索该方法,如果找到,则使用myFooId作为其第一个参数来调用Foo方法。
这意味着,您应该能够Foo.myFoos.example.parentMethodX('bar', 'baz')

var Foo = function() {

  // parent instance
  _self = this;

  // custom elements dictionary
  _myFooItems = {};

  // to call parent methods directly on custom elements
  this.myFoos = Object.create(new Proxy({}, {

      // property getter function (proxy target and called property name as params)
      get: function(target, myFooName) {

        // whether called property is a registered foo
        if (_myFooItems.hasOwnProperty(myFooName)) {

          // create another proxy to intercept method calls on previous one
          return Object.create(new Proxy({}, {

              // property getter function (proxy target and called property name as params)
              get: function(target, methodName) {

                // whether parent method exists
                if (_self.hasOwnProperty(methodName)) {

                  return function(/* arguments */) {

                    // insert custom element ID into args array
                    var args = Array.prototype.slice.call(arguments);
                    args.unshift(_myFooItems[ myFooName ]);

                    // apply parent method with modified args array
                    return _self[ methodName ].apply(_self, args);
                  };
                } else {

                  // parent method does not exist
                  return function() {
                    throw new Error('The method ' + methodName + ' is not implemented.');
                  }
                }
              }
            }
          ));
        }
      }
    }
  ));


  // register a custom foo and its ID
  this.registerFoo = function(myFooName, id) {

    // whether the foo has already been registered
    if (_myFooItems.hasOwnProperty(myFooName)) {
      throw new Error('The Foo ' + myFooName + ' is already registered in this instance.');
    }

    // register the foo
    _myFooItems[ myFooName ] = id;

    // return the created foo for further use
    return this.myFoos[ myFooName ];
  };
};

module.exports = Foo;

如果您运行代码并尝试注册 foo (上面的代码在 Node>=6.2.0 中工作),会发生什么情况,但会抛出以下错误:

> var exampleFoo = Foo.registerFoo('exampleFoo', 123456)
Error: The method inspect is not implemented.
  at null.<anonymous> (/path/to/module/nestedProxyTest.js:40:31)
  at formatValue (util.js:297:21)
  at Object.inspect (util.js:147:10)
  at REPLServer.self.writer (repl.js:366:19)
  at finish (repl.js:487:38)
  at REPLServer.defaultEval (repl.js:293:5)
  at bound (domain.js:280:14)
  at REPLServer.runBound [as eval] (domain.js:293:12)
  at REPLServer.<anonymous> (repl.js:441:10)
  at emitOne (events.js:101:20)

在花了很多时间思考为什么第二个代理甚至尝试调用一个方法(如果没有给它)时,我最终放弃了。我希望 exampleFoo 是一个代理对象,在调用时接受 Foo 方法。
是什么导致了这里的实际行为?

最佳答案

我认为你根本不应该在这里使用代理。假设你有一个可怕的 API

class Foo {
    …
    myApiMethod(id, …) { … }
    … // and so on
}

那么实现您正在寻找的目标的最干净的方法是

const cache = new WeakMap();
Foo.prototype.register = function(id) {
    if (!cache.has(this))
        cache.set(this, new Map());
    const thisCache = cache.get(this);
    if (!thisCache.get(id))
        thisCache.set(id, new IdentifiedFoo(this, id));
    return thisCache.get(id);
};

class IdentifiedFoo {
    constructor(foo, id) {
        this.foo = foo;
        this.id = id;
    }
}
Object.getOwnPropertyNames(Foo.prototype).forEach(function(m) {
    if (typeof Foo.prototype[m] != "function" || m == "register") // etc
        return;
    IdentifiedFoo.prototype[m] = function(...args) {
        return this.foo[m](this.id, ...args);
    };
});

这样你就可以做到

var foo = new Foo();
foo.myApiMethod(id, …);
foo.register(id).myApiMethod(…);

关于javascript - 嵌套 ES6 代理未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37610014/

相关文章:

javascript - AngularJS应用程序在登录后重定向

javascript - 导航栏上的悬停移动问题

javascript - 当尝试 Console.log 函数的结果时,我得到了未定义的结果

node.js - Meteor CMS 两个应用程序或多合一应用程序

未添加 Javascript 对象属性

javascript - 将对象数组减少/过滤为新的对象数组。

javascript - Canvas 动画在 FireFox 中卡顿,但在 Chrome 中完美

javascript - 从 html 文件执行 Nodejs 脚本

javascript - 如何过滤子对象的属性并返回带有通过 Javascript 过滤器的子对象的父对象?

javascript - 如何使用javascript获取并返回数组的每个最后一个字符为大写?