LoginSignup
3
3

More than 5 years have passed since last update.

Javascriptでrubyのmethod_missing的なことをして関数の引数を受け取る

Last updated at Posted at 2016-03-30

Direct Proxiesでmethod missing的なことをやる - Qiitaにずばりな記事があるんですがJavascript初心者としては「あれ、関数の引数どうすれば受け取れるんだろう?」と思ったわけです。

それで検索してみたらずばりな質問がありました。
javascript - How do I trap arguments to a target method when using a Proxy object? - Stack Overflow

2つの記事を参考にして書いてみたらできました。

var proxyCore = {
  get: function( target, property ) {
    return !(property in target) && (typeof target.propertyMissing === 'function') ? target.propertyMissing(property) : target[property];
  }
}

var PEPPERCore = {
  propertyMissing: function(name) {
    service = new Proxy({
      propertyMissing: function(methodName) {
        return function() {
          console.log("service:", name.replace(/^al/, "AL"));
          console.log("method:", methodName);
          console.log("arguments:", arguments);
        }
      }
    }, proxyCore);
    return service;
  }
}


var PEPPER = new Proxy(PEPPERCore, proxyCore);
PEPPER.alAnimatedSpeech.say("test");
// =>
// service: ALAnimatedSpeech
// method: say
// arguments: ["test"]
3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3