带有子方法的方法链接

method chaining with sub-methods

本文关键字:方法 链接 子方法      更新时间:2023-09-26

我试图使用子方法方法链。

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

问题是stuff()需要引用bar("bar")的值

是否有this.callee或其他类似的参考来实现这一点?

有这个吗?Callee或其他类似的参考来实现这一点?

不,你必须让foo返回一个具有do属性的对象,它要么:

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

  2. foo("bar")中的信息作为do的属性,然后通过thisdo对象中引用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>

尝试将do, stuff设置为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())