Skip to content Skip to sidebar Skip to footer

Method Chaining With Sub-methods

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

Solution 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:functionfoo1(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):functionDo(arg) {
  this.arg = arg;
}
Do.prototype.stuff = function() {
  snippet.log("The argument to foo2 was: " + this.arg);
};
functionfoo2(arg) {
  return {
    do: newDo(arg)
  };
}
foo2("bar").do.stuff();
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --><scriptsrc="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

Solution 2:

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

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

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

Post a Comment for "Method Chaining With Sub-methods"