[Series -04 for ES6] no longer chaos "wow": the alternative of using let var const

[Original] code road workers Coder-Power

Hello everyone, here is the code the road workers have the power, I am yards road worker, you are the power.

github-pages
blog Park cnblogs


Today's content, JavaScript changes on defined variables (in fact inaccurate, functions, constants represent the cold).


First, review under the vardefinition of problems

1. wow. . var mess. .

1.1 can repeat the definition

/* eg.0
    * multi-definition of var-variable
    */
//--------------------------------------
var band = "The Beatles"
var band = "The Scorpions"

console.log(band)     // Scorpions
//--------------------------------------

The above code does not error, but to print out the contents of the second definition Scorpions. .. In this C#and other languages must be unimaginable.

JS: hey miserable childhood, Forget the past. Although designed some simple rough, but easy to use them ah, through our efforts, as a high handsome rich Web era. Now rich, beauty health make up ~ ~ ~

1.2 can be defined after the first use

/* eg.1
    * use before be definied
    */
//--------------------------------------
age = 18
console.log(age)        // 18
var age = 10
console.log(age)        // 10
//--------------------------------------

This is the variable lift it. At compile time, will first varvariable defined on top, but this time no value, or undefinedthe assignment order of 18> 10, the printing result with an upper exemplary embodiment annotation.

Here, there is a priority issue, function > variablethat function is greater than ordinary variables.

No block-level scope 1.3

/* eg.2
    * [var]use before variable be definied
    */
//--------------------------------------
function foo() {
    var band = "Michael Learn To Rock"
}

console.log(band)        // Michael Learn To Rock
//--------------------------------------

Block-level scope should have: if(boolVal){ 这里 }, , for(...){ 这里 }and function(){ 这里 }, in fact, if not a direct function of a pair of curly braces also produce block-level place.

varNo block-level scope means that can be accessed outside the block level. The results in the previous example illustrates this point.

IIFE (Immediately Invoked Function Expression) function is executed immediately find out (ready to introduce separately later in this article).


Then let's take a look at what brought ES6

2. let const to save

2.1 letand consthas a block-level scope

I no longer worry code hemp hurt in the dark:

Scope is defined at the block level is not modified external access.

/* eg.3
    * can not access out of block
    */
//--------------------------------------
// eg.3.1
function music() {
    let band = "Mr. Big"
    const songs = ["The chain", "To be with you", "Wild world"]

    this.data = {
        band,songs
    }
}
console.log(band, songs)
// Uncaught ReferenceError: band is not defined
//--------------------------------------

The above direct print error, the function is not accessible outside to the inside with a let/constdeclared variable / constant.

Expand it: but can be bound to object properties, property itself externally visible. The following example (embodiment on the basis):

// eg.3.2
let m = new music()
console.log(m.data)
// { band: 'Mr. Big', songs: [ 'The chain', 'To be with you', 'Wild world' ] }

2.2 letand constthere does not exist a variable lift

trick or treat. To use the first definition.

/* eg.4
    * [let/const]use after be definied
    */
//--------------------------------------
// eg.2.1
band = "Queen"
let band
// Uncaught ReferenceError: Cannot access 'band' before initialization

// eg.2.2
song = "Bohemian Rhapsody"
const song
// Uncaught SyntaxError: Missing initializer in const declaration
//--------------------------------------

Undefined first use? It is given directly to you. (See, misstatements is not the same, will be mentioned below)

2.3 letand constcan not be redefined

/* eg.4
    * [let/const]can not defined duplicately
    */
//--------------------------------------
// eg.4.1
let band = "Guns&Rose"
let band = "Nirvana"
// Uncaught SyntaxError: Identifier 'band' has already been declared

// eg.4.2
const song = "November Rain"
const song = "Smells Like Teen Spirit"
// Uncaught SyntaxError: Identifier 'song' has already been declared
//--------------------------------------

Simple rules need no explanation. I am your only!

2.4 let define the variable

/* eg.5
    * [let/const]can not defined duplicately
    */
//--------------------------------------
let singer = "Bob Dylan"
console.log(singer)     // Bob Dylan

singer = "Bryan Adams"
console.log(singer)     // Bryan Adams
//--------------------------------------

Variable is indeed variable.

Note: When a string like the value, the address stored in the stack, the stack remains constant pool, compare the word face amount of time, than the address will therefore congruent (===), and again assign values ​​to variables change It is an address pointing to the original string constant pool / value still exists (other references are not recovered).

On ==and ===before you can see the hair of another article [transfer] [AboutEqual].

2.5 const define constants

JS: Finally we have a constant ( C#Lane also called const)

2.5.1 constant defines immutable

/* eg.6
    * use before be definied
    */
//--------------------------------------
// eg.6.1
const band = "The Eagles"
band = "The Beatles"
// TypeError: Assignment to constant variable.

// eg.6.2
const age = 18
age = 10
// TypeError: Assignment to constant variable.
//--------------------------------------

Small two examples above, or a constant string value described in the definitions are no longer changed.

Note: This refers to simple immutable type, complex type member / inside the objects / attributes can be changed.

/* eg.7
    * change the value of const-object's property
    */
//--------------------------------------
const person = {
    name = "Eagles",
    age = 18
}
console.log(person) 
// { name: 'Eagles', age: 18 }

person.name = "Chicken"
person.age = 10
console.log(person) 
// { name: 'Chicken', age: 10 }
//--------------------------------------

Print above results show that constproperties of the object name/agemodification success.

2.5.2 When constants defined in the assignment and only (= initial value to be assigned is defined, can not be changed after the assignment)

/* eg.8
    * exception on define const
    */
//--------------------------------------
const foo
foo = "bar"
// SyntaxError: Missing initializer in const declaration
//--------------------------------------

Without explanation, reported the anomaly. The definition constmust be given value. (As already mentioned, when a deeper impression on repeat it)


(Example seems to expose a portion of the playback history .. Interested students can look at Soso)


I hope you can help, next goodbye.


Welcome attention to sharing, learning together to improve it.


Guess you like

Origin www.cnblogs.com/CoderMonkie/p/es6-about-let-and-const.html