【问题标题】:method chaining with sub-methods方法链与子方法
【发布时间】:2015-10-03 05:59:28
【问题描述】:

我正在尝试将方法链与子方法一起使用。

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

catch是stuff()需要有对bar("bar")的值的引用

是否有任何this.callee 或其他此类参考来实现这一目标?

【问题讨论】:

  • 你这里指的是流畅的API吗?
  • do 是一个属性还是你错过了像..do().stuff() 这样的函数的拼写?
  • do 是一个属性,这就是为什么这有点挑战性。
  • @xyz 正如 crowder 所说,这不会有什么不同。
  • 好吧,你必须自己提供任何上下文。

标签: javascript methods method-chaining


【解决方案1】:

是否有任何 this.callee 或其他类似的引用来实现这一点?

不,您必须让 foo 返回一个带有 do 属性的对象,或者:

  1. 使stuff 成为对foo 的调用的闭包

  2. foo("bar") 获取您想要的信息作为do 的属性,然后通过do 对象通过this 引用stuff 中的该信息,或者

// 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】:

    尝试将dostuff 设置为foo 的属性,在stuff 处返回传递给foo 的参数,从foo 返回this

    var foo = function foo(args) {
      this.stuff = function() {
        return args
      }
      this.do = this;
      return this
    }
    
    console.log(foo("bar").do.stuff())

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-16
      • 2020-11-07
      • 1970-01-01
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多