68 effective ways to write high-quality JS code (VI)

Source: Internet
Author: User

[20141213] 68 effective ways to write high-quality JS code (VI)

No.26, using the Bind method to implement the function currying

Tips:

    1. Use the Bind method to implement the function curry, that is, to create a fixed demand parameter subset of the delegate function
    2. Pass null or undefined as the receiver's parameter to implement the function's curry, ignoring its receiver

What is the function of curry?

The technique of binding a function to a subset of its parameters is called function curry, which is a concise way to implement a function delegate with fewer references.

//有一个组装URL的JS函数function bulidURL(protocol, domain, path){    return protocol + ‘://‘ + domain + ‘/‘ + path;}//需要一个path数组转换为url数组,那么一般做法是:var urls = paths.map(function(path){    return bulidURL(‘http‘, ‘www.hstar.org‘, path);});如果用bind实现函数柯里化,则是:var buildURL2 = buildURL.bind(null, ‘http‘, ‘www.hstar.org‘);var urls = paths.map(buildURL2);其中由于buildURL不引用this,那么在bind中使用null,忽略函数本身的接收者,然后用bind实现柯里化。使用buildURL.bind的参数+buildURL2的参数结合起来调用buildURL方法。可以在bulidURL中写console(arguments)来查看参数合集。
No.27, using closures instead of strings to encapsulate code

Tips:

    1. Never include a local variable reference in a string when passing a string to the Eval function to execute their API
    2. An API that accepts function calls is better than an API that uses the Eval function to execute strings

In JS, a function is a convenient way to store code as a data structure that can be executed later. So it is possible to write high-performance high-order functions in JS, such as Map,foreach.

Bad design, use the Eval function to execute the string.

//定义一个函数,使用eval执行字符串function fun1(code){    eval(code);}//用法一:var val = 0;fun1(‘console.log(val)‘);//用法二:function fun2(){    var val = 1;    fun1(‘console.log(val)‘);}fun2(); //Error:val is not defined

Warning: When using eval, the scope is the global scope (window), such as the invocation of use one, just can produce normal results, if transferred to the function body, such as the use of two calls, there will be an error; the worst case scenario is when you use two calls, A variable with the same name on the global scope (in this case, Val) will make the result unpredictable.

The good thing is that the direct transfer function

function fun1(){}function fun2(p, action){    if(p === 1){        action();    }}fun2();
No.28, do not rely on the ToString method of the Function object

Tips:

    1. Calling the ToString method of the function does not require the JavaScript engine to obtain the exact source code of the function.
    2. Since the results of the ToString method may vary in different engines, never trust the details of the source code of the function
    3. The results of the ToString method do not expose local variable values stored in closures
    4. Typically, you should avoid using the ToString method of a Function object

JavaScript functions have an extraordinary feature of the ability to reproduce their source code as a string. However, the ECMAScript standard does not require any strings returned by ToString, so different engines may produce different results. Even returning to the string and the function is not relevant

No.29, avoid using non-standard stack check properties

Tips:

    1. Avoid nonstandard arguments.caller and Arguments.callee attributes because they do not have good portability
    2. Avoid using nonstandard function object Caller property, because it is unreliable in containing all stack information

Basic error (not recommended)

function getCallStack(){    var stack = [];    for(var f = getCallStack.caller; f; f = f.caller){        stack.push(f);    }    return stack;}

Warning: This function is very fragile, and if more than one time is present in a function 叜 call stack, the stack check will fall into a dead loop. Also use caller in ES5 Strict mode will be error.

68 effective ways to write high-quality JS code (VI)

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.