JavaScript Base Object creation mode chained invocation pattern (Chaining pattern) (029)

Source: Internet
Author: User

The chained invocation pattern allows a method to call an object one after the other. This mode does not consider saving the return value of the function, so the entire invocation can be done in the same line:

Myobj.method1 ("Hello"). Method2 (). METHOD3 ("World"). METHOD4 ();

If there are methods in the object that do not require a return value, you can let it return the this reference, which makes it easy to continue calling the next method:

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 Callsobj.increment (). Add (3). Shout (); 5//as opposed to calling them one by Oneobj.increment (); Obj.add (3); Obj.shout (); 5
The benefit of chained invocation patterns is that the code reads like a normal sentence, and also encourages programmers to write a more single, modular approach; The disadvantage is that running multiple functions in a row is difficult to debug. However, it is always convenient to return a method that does not require a return value. Many JavaScript libraries, such as jquery, use this pattern extensively.

JavaScript Base Object creation mode chained invocation pattern (Chaining pattern) (029)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.