method chaining with sub-methods

2019-09-11 06:14发布

问题:

I am trying to use method chain with sub-methods.

IE: foo("bar").do.stuff()

The catch is stuff() needs to have a reference to the value of bar("bar")

Is there any this.callee or other such reference to achieve this?

回答1:

Is there any this.callee or other such reference to achieve this?

No, you'd have to have foo return an object with a do property on it, which either:

  1. Make stuff a closure over the call to foo

  2. Have information you want from foo("bar") as a property of do, and then reference that information in stuff from the do object via this, or

// Closure example:
function foo1(arg) {
  return {
    do: {
      stuff: function() {
        snippet.log("The argument to foo1 was: " + arg);
      }
    }
  };
}
foo1("bar").do.stuff();

// Using the `do` object example (the `Do` constructor and prototype are just
// to highlight that `stuff` need not be a closure):
function Do(arg) {
  this.arg = arg;
}
Do.prototype.stuff = function() {
  snippet.log("The argument to foo2 was: " + this.arg);
};
function foo2(arg) {
  return {
    do: new Do(arg)
  };
}
foo2("bar").do.stuff();
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>



回答2:

Try setting do , stuff as properties of foo , return arguments passed to foo at stuff , return this from foo

var foo = function foo(args) {
  this.stuff = function() {
    return args
  }
  this.do = this;
  return this
}

console.log(foo("bar").do.stuff())