函数内函数的参数

时间:2014-08-31 10:08:11

标签: javascript

如何将函数“链接”,以便像这样调用此函数

F('Test').custom_substring(0,1);

3 个答案:

答案 0 :(得分:2)

您必须返回一个具有名为custom_substring的方法成员的对象。一个例子:

var F = function(){
  return {
    custom_substring:function(){
      console.log('custom substring');
      return this;
    }
  }
}

F('Test')
  .custom_substring(0,1)
  .custom_substring(0,1)
  .custom_substring(0,1);

要创建对象,您可以使用构造函数和原型,这是一个复杂的主题并解释here

我不会乱用String.prototype,因为breaks encapsulation

答案 1 :(得分:1)

以下示例提供了一个可链接的custom_substring,它不会修改原始对象,而是返回一个新对象。这类似于jQuery和其他库的工作方式(以及内置字符串操作的工作原理),它有助于实现更安全,更可预测的代码。

function F(str) {
    return {
        toString: function () { return str; },

        // You didn't provide an example of what you want custom_substring
        // to do, so I'll have it append a "!" to the beginning of the resulting value
        // (since I can't think of anything else for it to do)
        custom_substring: function (from, to) {
            return F("!" + str.substring(from, to));
        }
    };
}

var s1 = F("Hello everyone");
var s2 = s1.custom_substring(0, 7);
var s3 = s2.custom_substring(0, 5)
           .custom_substring(0, 4);

console.log(s1);  // Hello everyone
console.log(s2);  // !Hello e
console.log(s3);  // !!!He

答案 2 :(得分:-1)

如果您真的想要创建链式加载,则需要始终从可能的方法返回this

例如,我们有一些类有一些方法:

function Foo() {
    this.foo = 'bar';
    return this;
}

Foo.prototype = Object.create({
    sayFoo: function() {
        console.log(this.foo);
        return this;
    },

    getFoo: function() {
        return this.foo; // Here you can't make chainload
    },

    saySmth: function() {
        console.log('Something');
        return this;
    }
});

我们可以使用它:

var test = new Foo().sayFoo().saySmth().getFoo(); // prints this.foo -> 'Something' -> returns this.foo
console.log(test); // prints out this.foo