How to make chainable function in JavaScript?

前端 未结 2 1473
执念已碎
执念已碎 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:39

    Sure, the trick is to return the object once you're done modifying it:

    String.prototype.foo = function() {
        return this + "+";
    }
    
    var str = "Notepad";
    console.log(str.foo().foo().toUpperCase());
    

    http://jsfiddle.net/Xeon06/vyFek/

    To make the method available on String, I'm modifying it's prototype. Be careful not to do this on Object though, as it can cause problems when enumerating over their properties.

提交回复
热议问题