Search code examples
javascriptnode.jschaining

Chaining methods in Javascript


I want to chain methods in Javascript (using Node.js).

However, I encountered this error:

var User = {
    'deletes': function() {
        console.log('deletes');
        return this;
    },
    'file': function(filename) {
        console.log('files');
    }
};

User.deletes.file();


node.js:50
    throw e; // process.nextTick error, or 'error' event on first tick
    ^
TypeError: Object function () {
        console.log('deletes');
        return User;
    } has no method 'file'
    at Object.<anonymous> (/tests/isolation.js:11:14)
    at Module._compile (node.js:348:23)
    at Object..js (node.js:356:12)
    at Module.load (node.js:279:25)
    at Array.<anonymous> (node.js:370:24)
    at EventEmitter._tickCallback (node.js:42:22)
    at node.js:616:9

How could I make it work?


Solution

  • You are not invoking the deletes function (the string representation of the function is what is printed in the error trace).

    Try:

    User.deletes().file()
    

    Happy coding.