0

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?

7
  • Is it a fluent API you're referring to here? Commented Oct 3, 2015 at 6:02
  • Is do is a property or you miss spelled it for function like ..do().stuff()? Commented Oct 3, 2015 at 6:02
  • do is a property, that's why this is a bit challenging. Commented Oct 3, 2015 at 6:03
  • @xyz as crowder said, that wouldn't make a difference. Commented Oct 3, 2015 at 6:04
  • Well, you will have to provide any context yourself. Commented Oct 3, 2015 at 6:06

2 Answers 2

3

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>

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.