zoukankan      html  css  js  c++  java
  • JavaScript基础对象创建模式之链式调用模式(Chaining Pattern)(029)

    链式调用模式允许一个接一个地调用对象的方法。这种模式不考虑保存函数的返回值,所以整个调用可以在同一行内完成:

    myobj.method1("hello").method2().method3("world").method4();
    

    如果对象中有些方法不需要有返回值,就可以让它返回this引用,这个this引用就可以方便继续调用下一个方法:

    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
    
     
    链 式调用模式的好处是代码读起来像是普通的句子,而且也鼓励编程人员写出功能更单一,更模块化的方法;缺点则是一行里运行多个函数难于debug。不管怎 样,不需要返回值的方法返回this总是能提供便利的。许多JavaScript库,如JQuery就大量使用了这种模式。
  • 相关阅读:
    JAVA变量的作用域
    SQLite
    ajax
    浏览器调试
    SQL链接
    Computer
    Sql知识点总结
    Web Socket
    秒杀
    副业
  • 原文地址:https://www.cnblogs.com/Bryran/p/3976155.html
Copyright © 2011-2022 走看看