Chaining methods in Javascript

社会主义新天地 提交于 2019-12-11 11:25:29

问题


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?


回答1:


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.




回答2:


One thing is missing: User.deletes().file(<filename>). I'm not sure, maybe this raise an error?



来源:https://stackoverflow.com/questions/4131374/chaining-methods-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!