惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
GbyAI
GbyAI
MongoDB | Blog
MongoDB | Blog
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio Blog
腾讯CDC
G
Google Developers Blog
宝玉的分享
宝玉的分享
I
InfoQ
F
Fortinet All Blogs
Engineering at Meta
Engineering at Meta
Vercel News
Vercel News
云风的 BLOG
云风的 BLOG
博客园 - 【当耐特】
酷 壳 – CoolShell
酷 壳 – CoolShell
Google DeepMind News
Google DeepMind News
阮一峰的网络日志
阮一峰的网络日志
罗磊的独立博客
IT之家
IT之家
D
DataBreaches.Net
Martin Fowler
Martin Fowler
月光博客
月光博客
Hugging Face - Blog
Hugging Face - Blog

博客园 - 小郝(Kaibo Hao)

Big O Complexity Chart (From: bigocheatsheet.com) Machine Learning Note - Note 1 JavaScript Patterns 7.1 Singleton JavaScript Patterns 6.7 Borrowing Methods JavaScript Patterns 6.6 Mix-ins JavaScript Patterns 6.5 Inheritance by Copying Properties JavaScript Patterns 6.4 Prototypal Inheritance JavaScript Patterns 6.3 Klass JavaScript Patterns 6.2 Expected Outcome When Using Classical Inheritance JavaScript Patterns 6.1 Classical Versus Modern Inheritance Patterns JavaScript Patterns 5.9 method() Method JavaScript Patterns 5.7 Object Constants JavaScript Patterns 5.6 Static Members JavaScript Patterns 5.5 Sandbox Pattern JavaScript Patterns 5.4 Module Pattern JavaScript Patterns 5.3 Private Properties and Methods JavaScript Patterns 5.2 Declaring Dependencies JavaScript Patterns 5.1 Namespace Pattern JavaScript Patterns 4.10 Curry
JavaScript Patterns 5.8 Chaining Pattern
小郝(Kaibo Hao) · 2014-07-03 · via 博客园 - 小郝(Kaibo Hao)

2014-07-03 23:20  小郝(Kaibo Hao)  阅读(287)  评论()    收藏  举报

Chaining Pattern - Call methods on an object one after the other without assigning the return values of the previous operations to variables and without having to split your calls on multiple lines.

var obj = {

    value: 1,

    increment: function () {

        this.value += 1;

        return this;

    },

    add: function (v) {

        this.value += v;

        return this;

    },

    shout: function () {

        alert(this.value);

    }

};

// chain method calls

obj.increment().add(3).shout(); // 5

// as opposed to calling them one by one

obj.increment();

obj.add(3);

obj.shout(); // 5

Pros and Cons of the Chaining Pattern

Pros

  1. save some typing and create more concise code that almost reads like a sentence.
  2. splitting your functions and creating smaller, more specialized functions, as opposed to functions that try to do too much. This improves the maintainability in the long run.

Cons

  debug code written this way which it's hard to check which part is wrong in the same line.

References: 

JavaScript Patterns - by Stoyan Stefanov (O`Reilly)