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

Source: Internet
Author: User

no.51, an array method that is common to a dependency on a class array object

Tips:

    1. For a class array object, by extracting the method object and using its call method to use the universal array method
    2. Any object that has an indexed property and an appropriate length property can use the universal array method

The standard methods in Array.proteotype are designed to be reusable by other objects, even if they do not inherit the array. A very practical example of arguments this is the following example:

//definefunction fun(){  console.log(arguments);  // [1, 2, 3]  console.log(arguments instanceof Array) // false  arguments.forEach(function(argv){  //TypeError    console.log(argv)  });}//callfun(1, 2, 3);

As a result, the output arguments and arrays are very similar, and by instanceof, it is not an array, so arguments is a class array object, but it is typeerror when the foreach is executed. Why

Because arguments there is no inherited Array.prototype, the Foreach method cannot be called directly, but the reference to the Foreach method can be extracted and invoked using its call, the code is as follows:

//definefunction fun(){  [].forEach.call(arguments, function(argv){    console.log(argv);  });}//callfun(1, 2, 3);

In addition to arguments, Dom's nodelist is also a class array object:

var nodes = document.getElementsByTagName(‘a‘);console.log(nodes);console.log(nodes instanceof Array); // false

So, how do you make an object "look like an array"? The following two rules are available:

    1. Has an integer length property that ranges from 0 to 2^32-1
    2. The length property is greater than the maximum index of the object. An index is an integer in the range of 0 to 2^32-2, whose string represents a key to the object.

Given the above rules, we can create our own class array objects ourselves:

var arrayLike = {0: ‘a‘, 1: ‘b‘, 2: ‘c‘, length: 3};var result = [].map.call(arrayLike, function(el){  return el.toUpperCase();});console.log(result); // [‘A‘, ‘B‘, ‘C‘]

In special cases, the array join method concat is not completely generic. Because it examines the [[Class]] property of the object, in order to connect the class array object, we need to first process the array of classes into arrays:

var arrLike = {0: ‘a‘, length: 1};var arr = [].slice.call(arrLike);console.log([‘A‘].concat(arr)); // [‘A‘, ‘a‘]
no.52, array literals are better than array constructors

Tips:

    1. If the first parameter of an array constructor is a number then the constructor behavior of the array is different
    2. Use array literals instead of array constructors

The reasons are as follows:

[] Simpler than the new array

var arr = [];var arr = new Array();

With the new array (), you must make sure that no one has re-wrapped the array variable

funciton f(Array){    return new Array(1, 2, 3, 4, 5);}f(String); //new String(1)

With the new array (), you must make sure that no one has modified the global array variable

Array = Stringnew Array(1, 2, 3); // new String(1)

When using the new array, the first parameter type is different, resulting in a ambiguity

new Array(‘hello‘) 和 [‘hello‘] 等价[1] 和 new Array(1) 不等价,前者创建包含元素的1的数组,后则创建长度为1的数组。

Therefore, the literal is preferred, because the array literal has more canonical, more consistent semantics.

No.53, keeping a consistent agreement

Tips:

    1. Using a consistent convention in variable naming and function signing
    2. Do not deviate from the conventions that users are likely to encounter in their development platform

Have good coding habits, use the industry's regular coding specifications, and pay attention to the order of parameters. In a nutshell: Keep your code consistent .

no.54, undefined as "no value"

Tips:

    1. Avoid using undefined to represent any non-specific value
    2. Use a descriptive string value or an object that names a Boolean property instead of using undefined or null to represent a specific app flag
    3. The default value for the supplied parameter should be in the way of test undefined, rather than checking arguments.length.
    4. In a place where 0, Nan, or an empty string is a valid parameter, you should never implement a parameter default value by using a truth test.

Undefined is special, and undefined is not created when JavaScript cannot provide a specific value. If only the variable is defined, it is not assigned, or there is no attribute in the object, and the function has no return statement will produce undefined.

var x;console.log(x); //undefinedvar o = {};console.log(o.p1); //undefinedfunction fun(){}console.log(fun()); //undefined

The function parameter value is undefined if no argument is supplied to the function parameter

function fun(x){    return x;}console.log(fun()); //undefined

It is a convention to regard undefined as a lack of a particular value. There is a high risk of using it for other purposes:

//假设highlight为设置元素高亮element.highlight(‘yellow‘); //设置为黄色//如果要设置为随机颜色//方式一、如果遇到undefined则设置为随机element.highlight(undefined);//这样的方式通常会产生歧义element.highlight(config.highlightColor);//使用如上语句时,我们的期望一般是没有提供配置则使用默认色,但是由于undefined代表随机,那么破坏了这种常规思维。让代码变得难以理解。//更好的做法element.highlight(‘random‘);//或者是element.highlight({random: true});

Another place to watch out for undefined is the implementation of optional parameters.

function fun(a, b){  if(arguments.length < 2){    b = ‘xx‘;  }}

If you use Fun (a), the call is basically the same as expected, but if you use fun (A, ' undefind '), then the statement within if is not executed, resulting in an error, if the test is undefined helps to build a more robust API.

Another logical alternative to the optional parameter is:

function fun(a, b){  b = b || ‘xxx‘;}

Be aware, however, that the truth test is not always safe. If a function should accept an empty string, 0,nan is a valid value, then the truth test should not be used.

//Bad Usefunction Point(x, y){  this.x = x || 200;  this.y = y || 200;}

What's wrong with the above code, because using new point (0, 0) causes the default value to be used, which deviates from expectations. So more rigorous testing is required:

function Point(x, y){  this.x = x === undefined ? 200 : x;  this.y = y === undefined ? 200 : y;}
no.55, the option object that receives the keyword parameter

Tips:

    1. More readable and easier to remember with option object-like APIs
    2. All parameters provided through the option object should be considered optional
    3. Use the Extend function to abstract logic that extracts values from an option object

Let's start with a complex function call:

fun(200, 200, ‘action‘, ‘green‘, true);

A glance, completely unintelligible. When it comes to the convenience of the optional parameters of C #, it would be nice to think of JavaScript as such.

Fortunately, JavaScript provides a simple, lightweight idiom: an option object. The effect of the optional parameter is basically reached.

fun({  width: 200,  height: 200,  action: ‘action‘,  color: ‘green‘,  ignoreError: true});

Relatively, more cumbersome, but easier to read. Another benefit is that the parameters are optional.

If there is a required parameter, then when designing the API. It is recommended that they be independent of options, and other languages can draw on this idea.

// options 为可选参数function fun(width, height, options){}

By combining optional and default parameters with extend, you can make your functions concise and robust.

function fun(width, height, options){  var defaults = {    color: ‘green‘,    ignoreError: false,    action: ‘‘  }  //$.extend 可以理解为jQuery的方法  options = $.extend({}, defaults, options);  //do something...}

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

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.