Javascript (五):Scope

Scope

In javaScript, scope is the context in which code is executed.Typically, scope is used to define the extent of information hiding—that is, the visibility(可见性) or accessibility(可访问性) of variables from different parts of the program.

  • Global Scope
  • Function Scope
  • Block Scope
  • Lexical Scope
  • Dynamic Scope

Global Scope

The global scope is the last stop in the scope chain . Therefore, variables defined in the global scope can be accessed from anywhere . Danger is that any piece of code can change global variables for any reason at any time.

// g1 be created in global scope
var g1 = 123; 

// global scope
(function() {
    // g be created in global scope
    g2 = 123; 
})();

变量声明不推荐lack var。缺少var的变量被称为implied globalsimplied globals会污染全局环境、导致代码很难管理.

Read More...

Javascript (四):Deep Into 'Array'

Array.sort(comparator)

  • no comparator Array.sort() do string comparison(ASCII)

    [1, 2, 21, 3, -4].sort();
    //=> -4, 1, 2, 21, 3
  • self-define comparator

    var employees = [];
    employees[0] = {
    name: “George”,
    age: 32,
    retiredate: “March 12, 2014”
    };
    
    employees[1] = { name: “Edward”, age: 17, retiredate: “June 2, 2023” };
    employees[2] = { name: “Christine”, age: 58, retiredate: “December 20, 2036” };
    employees[3] = { name: “Sarah”, age: 62, retiredate: “April 30, 2020” };
    // retiredate ASC employees.sort(function(a, b) { return new Date(a.retiredate) - new Date(b.retiredate) });
    // age ASC employees.sort(function(a, b) { return a.age - b.age });
    类似

Read More...

Javascript (三):Constructor Function

Constructor function create multiple objects that share certain qualities and behaviors.Constructor function like cookie cutter.Specific constructor function like cookie cutter templdate

Native/Built-in Object Constructor

  • Number()
  • String()
  • Boolean()
  • Object()
  • Array()
  • Function()
  • Date()
  • RegExp()
  • Error()

Array()

Array is Constructor function.

/**
* @param {...*} [args]
* @constructor
* @template T
*/
function Array(args) {}

/**
* @param {...T|Array.} [items]
* @return {Array.}
*/
Array.prototype.concat = function(items) {};

Math

Static object for other methods

// Refer to ECMAScript,as Follows:
Math = {};

/**
* @param {number} x
* @static
* @return {number}
*/
Math.abs = function(x) {};