How to make chainable function in JavaScript?

前端 未结 2 1474
执念已碎
执念已碎 2020-11-28 10:13

Lets imagine function like this:

function foo(x) {
    x += \'+\';
    return x;
}

Usage of it would be like:

var x, y;
x =         


        
2条回答
  •  臣服心动
    2020-11-28 10:42

    If I remember correctly, you can use "this" as a context of a function (object it belongs to) and return it to make the function chainable. In other words:

    var obj = 
    {
        f1: function() { ...do something...; return this;},
        f2: function() { ...do something...; return this;}
    }
    

    then you can chain the calls like obj.f1().f2()

    Keep in mind, you won't be able to achieve what you are expecting by calling obj.f1().toUpperCase() - it will execute f1(), return "this" and will try to call obj.toUpperCase().

提交回复
热议问题