[Effective JavaScript notes] 60th: Support Method Chain

Source: Internet
Author: User

Part of the ability of a stateless API is the flexibility to break down complex operations into smaller operations. A good example of this is the Replace method of the string. Because the result itself is also a string, you can repeat the substitution for the previous replace operation. A common use case for this pattern is to replace a string with a special character letter before inserting a string into the HTML.

function escapeBasicHTML(str){    return str.replace(/&/g,"&amp;")              .replace(/< /g,"&lt;")              .replace(/>/g,"&gt;")              .replace(/"/g,"&quot;")              .replace(/‘/g,"&apos;");}

The first call to replace returns a string that replaces all special characters "&" with the Escape sequence "&" of the HTML string; This repetitive method call style is called the method chain. This style does not need to save the intermediate result as a variable, more concise. jquery is a good example.

function escapeBasicHTML(str){    var str2=str.replace(/&/g,"&amp;")    var str3=str2.replace(/< /g,"&lt;")    var str4=str3.replace(/>/g,"&gt;")    var str5=str4.replace(/"/g,"&quot;")    var str6=str5.replace(/‘/g,"&apos;");    return str6;}

Eliminating temporary variables makes the code more readable, and intermediate results are just one important step in getting the final result.
If an API produces an interface object, the method that invokes the interface object produces an object that has the same interface, then the method chain can be used. The array iteration method described in the previous 50 and 51 lines is another chained API.

var users=records.map(function(record){    return record.username;}).filter(function(username){    return !!username;}).map(function(username){    return username.toLowerCase();});

Because every iteration of the array, the return is an array. The array method can be easily used to process it.
This style is very flexible and expressive for the user of the API, so it is worthwhile to design the API to support this style.
Typically,
In a stateless API, if the API does not modify the object, but instead returns a new object, the chain gets a natural result. Therefore, the methods of the API provide more objects of a similar set of methods.
In stateful APIs, the trick here is that the method returns this when the object is updated, rather than undefined. This makes it possible to perform multiple updates of the same object with a sequence of chained method calls.

element.setBackgroundColor(‘yellow‘)       .setColor(‘red‘)       .setFontWeight(‘bold‘);

The methods of stateful APIs are sometimes referred to as fluency. If the Update method does not return this, then the caller of the API has to repeat the name of the object each time. If the object is simply named as a variable, this is no different. But when combined with stateless methods to retrieve updated objects, the method chain is very concise and the code is more readable. This approach is commonly used in jquery methods. It has a set of (stateless) methods for querying Web pages from user interface elements, and a set of (stateful) methods for updating those elements.

$(‘#notification‘)   .html(‘Server not responding.‘)   .removeClass(‘info‘)   .addClass(‘error‘);

The same object is returned by calling the stateful Html,removeclass,addclass method to support smooth, without creating a temporary variable to store the results of the query executed by the jquery function. If you feel that this style is not very familiar, you can also add intermediate variables to store the return values of each function.

var element=$(‘#notification‘);element.html(‘Server not responding.‘);element.removeClass(‘info‘);element.addClass(‘error‘);

By supporting the method chain, the API allows programmers to choose the style that they prefer. If the method returns undefined, the user is forced to use a more verbose style.

Tips
    • Using a method chain to connect stateless operations

    • Support for method chains by returning new objects in a stateless method

    • Supports the method chain by returning this in a stateful method

[Effective JavaScript notes] 60th: Support Method Chain

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.