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

Source: Internet
Author: User

[20141129] 68 effective ways to write high-quality JS code (IV)

No.16, avoid using eval to create local variables

Tips:

    1. Avoid variables created with the Eval function to pollute the caller scope.
    2. If the Eval function code could create a global variable, encapsulating this call into a nested function has prevented the scope from polluting.

When Eval is performed, the variables in eval are added to the scope (function scope)

function fun1(){    eval(‘var y = 1;‘);    console.log(‘fun1->y:‘+y); // ‘fun->y:1‘}fun1();console.log(‘global->y:‘+y); //throw Error

Do not pass the uncontrolled arguments directly to Eval, which may alter the scope object.

//Bad codevar g = ‘global‘;function fun2(code){    eval(code);}fun2(‘var g="local"‘);console.log(g) //‘local‘//Right codevar g = ‘global‘;function fun2(code){    (function(){        eval(code);    })();}fun2(‘var g="local"‘);console.log(g) //‘global‘,嵌套作用域

The above right Code, if you execute a variable declaration without VAR, it will also affect the global G object.

No.17, indirect call to eval function is better than direct invocation

Tips:

    1. Wrapping the Eval function with a meaningless literal is wrapped in a sequence expression to achieve the purpose of forcing the use of an indirect call to the Eval function
    2. Call the Eval function as indirectly as possible instead of calling the Eval function directly

Call Eval directly, then the compiler cannot optimize the JS code. How do I call eval indirectly?

No.18, Understanding function Invocation, method invocation, and constructor call differences

Tips:

    1. Method calls the object that will be found by the method property to invoke the receiver
    2. A function call takes a global object as its recipient. The function call syntax is rarely used to invoke a method
    3. The constructor needs to be called through the new operator, and the resulting object is created as its recipient

Functions that are defined directly on a global object are called functions, and the call is a function call

var fun1 = function(p){    console.log(p);};function fun2(p){    console.log(p);}//函数调用fun1(‘p1‘);fun2(‘p2‘);

If the property of an object is a function, then it is called a method, and the usage pattern is a method call

var obj = {    name: ‘Hello ‘,    fun1: function(name){        console.log(this.name + name);    }};//方法调用obj.fun1(‘Jay‘);

Note: The Name property of obj is accessed through this in fun1

The constructor call takes a completely new object as the value of the This variable

fucntion User(name, age){    this.Name = name;    this.Age = age;}//此时,user是一个全新的对象var user = new User(‘Jay‘, 23);
No.19, Master high-order function

Tips:

    1. Higher-order functions are those functions that use functions as parameters or return values
    2. Proficiency in higher-order functions of existing libraries
    3. Learn to find common coding patterns that can be replaced by higher-order functions

Requirement: Convert array elements all to uppercase

//常规做法var arr = [‘abc‘, ‘test‘, ‘123‘];for(var i =0, len = arr.length; i < len; i++){    arr[i] = arr[i].toUpperCase();}console.log(arr);//高阶函数var arr = [‘abc‘, ‘test‘, ‘123‘];arr = arr.map(function(item){    return item.toUpperCase();});console.log(arr);

Note: You need to be aware of the return value when the higher-order function is used, some to change the original object, some to return the new object

No.20, using the call method to customize the recipient to invoke the method

Tips:

    1. To invoke a function by using the call method to customize the recipient (personal understanding as a scope)
    2. Use the call method to invoke a method that does not exist in a given object
    3. Use the call method to define a higher order function to allow the consumer to assign a recipient to a callback function
function fun1(){    this.name = ‘Test‘;}var obj = {    name: ‘Jay‘};console.log(obj.name);fun1.call(obj);console.log(obj.name);

Call Function Invocation Method:

f.call(obj, p1, p2, p3);

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

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.