问题
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:
Make
stuff
a closure over the call tofoo
Have information you want from
foo("bar")
as a property ofdo
, and then reference that information instuff
from thedo
object viathis
, 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())
来源:https://stackoverflow.com/questions/32919441/method-chaining-with-sub-methods