ES6 (1):const/let

That can go to learn about ES6 Ruan Yifeng Great God ~ http://es6.ruanyifeng.com/#docs/let

Again personal record of learning to understand, the chapter on the order of a chapter of the book of God Ruanda record and practice

history:

ECMASCRIPT: Standard (specifications)

JAVASCRIPT: realization

After the release of ES5 collectively referred to as ES6 (ESMASCRIPT2015 later)

 

A, let / const: let only within the block is located (block-level scope, to prevent upward, mentioned in the previous article), an arrow is also true in the function, the role of the domain block-level function declaration of behavior similar to let, can not be cited in addition to block-level scope.

But for compatibility with older versions before, the browser may not achieve compliance with the above provisions.

To declare the function block-level role in the region, it should be written as a function expression, rather than a function declaration:

Expression: let x = function () {}

Declaration statement: function x () {}

 

const constant is read-only, its value can not be changed (must be initialized when declaring constants, otherwise an error).

 

 const ensure its preservation is of the same memory address, if not a simple data type, it may change.

 

Second, the top-level object

Browser: window

Node:global

var / function is a global variable declaration attribute is also top-level object, and let / const / class declaration of the global variables are not top-level objects.

Top:

let not belong to the top

 

 Also top-level object is not uniform:

Browser: window

Browsers and web worker: self directed top-level objects

node:global

 

In order to achieve compatibility: Using this, but this there are some small issues that need attention:

Global environment: this return to the top-level object. node, and this refers to the current module module es6

Function: If the application or the object is strongly bound, then perform this same top-level object (non-strict mode on before this can refer to the written essay)

new Function ( 'return this') () Returns the global object. (Try not to use personally feel that the way the statement constructor function)

Here is the book of God Ruanda Provision:

// 方法一
(typeof window !== 'undefined'
   ? window
   : (typeof process === 'object' &&
      typeof require === 'function' &&
      typeof global === 'object')
     ? global
     : this);

// 方法二
var getGlobal = function () {
  if (typeof self !== 'undefined') { return self; }
  if (typeof window !== 'undefined') { return window; }
  if (typeof global !== 'undefined') { return global; }
  throw new Error('unable to locate global object');
};

 

Guess you like

Origin www.cnblogs.com/jony-it/p/10930460.html