ES6經常使用語法

ES6 經常使用語法

  • 新增 let、const 命令 來聲明變量,和var 相比,let 聲明的變量不存在變量提高問題,但沒有改變JS弱類型的特色,依然能夠接受任意類型變量的聲明;const 聲明的變量不容許在後續邏輯中改變,提升了JS語法的嚴謹性。
  • 新增解構賦值、rest 語法、箭頭函數等,這些都是爲了讓代碼看起來更簡潔,而包裝的語法糖。
  • 新增模塊化機制,這是 JavaScript 走向規範比較重要的一步,讓前端更方便的實現工程化。
  • 新增類和繼承的概念,配合模塊化,JavaScript 也能夠實現高複用、高擴展的系統架構。
  • 新增模板字符串功能,高效簡潔,結束拼接字符串的時代。
  • 新增 Promise 機制,解決異步回調多層嵌套的問題。
  • 更多學習:點擊 

1、聲明變量const let var

  • var,變量提高,是全局做用域或函數做用域,var聲明的變量存在覆蓋現象
  • let,表示變量,是塊級做用域,好比一個函數內部,代碼塊{}內部,let不容許在相同做用域內,重複聲明同一個變量。
  • const,表示常量,是塊級做用域,好比一個函數內部,代碼塊{}內部,常量一旦聲明不可修改
  • ES5 只有全局做用域和函數做用域,沒有塊級做用域
<script>
{
    let x = 10;
    var y = 20;
}
console.log (x);  // ReferenceError: x is not defined
console.log (y);  // 20

console.log(a);  // undefined,var聲明變量以前可使用該變量
var a = 10;
console.log(b);  // ReferenceError: b is not defined,let聲明變量以前不可使用該變量
let b = 10;

//注意:let不容許在相同的做用域內重複聲明同一個變量。
function foo(){
    let x = 10;
    var x = 20;
}  // 報錯

function foo(){
    let y = 10;
    let y = 20;
}  // 報錯


//ES5中只有全局做用域和函數做用域,並無塊級做用域。
var name = 'Tom';

function foo(){
    console.log(name);
    if (false){
        var name = 'Bob'
    }
}
foo();  // undefined

/*出現上述現象的緣由就是在函數內部,因爲變量提高致使內存的name變量覆蓋了外層的name變量。
相似的狀況還出如今 for循環的計數變量最後會泄露爲全局變量。*/

for (var i=0;i<5;i++){
    console.log('哈哈');
}
console.log(i);  // 5

// ES6中的let聲明變量的方式實際上就爲JavaScript新增了塊級做用域。

var name = 'Tom';

function foo(){
    console.log(name);
    if (false){
        let name = 'Bob'
    }
}
foo();  // Tom

// 此時,在foo函數內容,外層代碼塊就再也不受內層代碼塊的影響。因此相似for循環的計數變量咱們最好都是用let來聲明。

var a = [];
for (var i = 0; i < 10; i++) {
    a[i] = function () {
        console.log(i)
    }
}
a[6]();  //10

//===============
var a = [];
for (let i = 0; i < 10; i++) {
    a[i] = function () {
        console.log(i)
    }
}
a[6]();  //6

//===============
var a = [];
for (let i = 0; i < 4; i++) {
    console.log(i)  // 0,1,2,3
}


/*
const用來聲明常量。const聲明變量必須當即初始化,而且其值不能再改變。
const聲明常量的做用域與let相同,只在聲明所在的塊級做用域內有效。
ES6規定:var命令和function命令聲明的全局變量依舊是全局對象的屬性;
let命令、const命令和class命令聲明的全局變量不屬於全局對象的屬性。
*/
const PI = 3.14;
var x1 = 10;
let y1 = 20;
window.x1  // 10
window.y1  // undefined
</script>
let&const

2、模板字符串

模板字符串(template string)是加強版的字符串,用反引號(`)標識。它能夠看成普通字符串使用,也能夠用來定義多行字符串,或者在字符串中嵌入變量javascript

?
1
2
3
4
5
6
7
8
9
10
<script type= "text/javascript" >
     var imgSrc = './1.jpg' ;
     $( function () {
         $( 'ul' ).append(`<li>
         <a href= "javascript:void(0);" >
             <img src=${imgSrc} alt= "" >
         </a>
         </li>`)
     });
</script>

3、箭頭函數

  • 若是參數只有一個,能夠省略小括號
  • 若是不寫return,能夠不寫大括號
  • 沒有arguments變量
  • 不改變this指向
  • 其中箭頭函數中this指向被固定化,不是由於箭頭函數內部有綁定this的機制。實際緣由是箭頭函數根本沒有本身的this,致使內部的this就是外層代碼塊的this。
  • 箭頭函數,this指向外層代碼塊的this
  • 普通函數,this指向調用它的對象,也就是person對象
<script>
var person = {
    name: 'Q1mi',
    age:18,
    func:function(){
        console.log(this);
    }
};
person.func()  // person對象   普通函數,this指向調用它的對象

var person = {
    name: 'Q1mi',
    age:18,
    func:()=>{
        console.log(this);
    }
};
person.func()  // window對象   箭頭函數,this指向外層代碼塊的this

</script>
View Code
<script type="text/javascript">
  
        // 普通函數
        function add(a,b) {
            return a+b;
        };
        alert(add(1,2));   
          
        // 函數對象
        var add  = function (a,b) {
            return a+b;
        };
        alert(add(3,4))
          
        // 箭頭函數
        var add = (a,b)=>{
            return a+b;
        };
        alert(add(3,7))
          
        var f = a => a
        //等同於
        var f = function(a){
           return a; 
        }
          
        //無形參
        var f = () => 5;
        // 等同於
        var f = function () { return 5 };
  
        //多個形參
        var sum = (num1, num2) => num1 + num2;
        // 等同於
        var sum = function(num1, num2) {
          return num1 + num2;
        };
  
        var person = {
            name:"alex",
            age: 20,
            fav:function () {
                // this指的是當前的對象,即便用它的對象 person對象
                console.log(this.age);
                console.log(arguments[0])
            }
        };
        person.fav();
       
        var person = {
            name:"alex",
            age: 20,
            fav: () => {
                // this的指向發生了改變,指向了定義時所在的對象window
                console.log(this);   //window
                console.log(arguments) //報錯
            }
        };
        person.fav();
         
        //這個箭頭函數的定義生效是在foo函數生成時,而它的真正執行要等到 100 毫秒後。若是是普通函數,執行時this應該指向全局對象window,這時應該輸出21。可是,箭頭函數致使this老是指向函數定義生效時所在的對象(本例是{id: 42}),因此輸出的是42。
        function foo() {
          setTimeout(() => {
            console.log('id:', this.id);
          }, 100);
        }
        var id = 21;
        foo.call({ id: 42 });
        // id: 42
 
        function foo() {
          setTimeout(function(){
            console.log('id:', this.id);
          }, 100);
        }
        var id = 21;
        foo.call({ id: 42 });
        // id: 21
</script>
View Code

4、對象

一、屬性簡潔表示法

<script>

// 屬性簡潔表示法  ES6容許直接寫入變量和函數做爲對象的屬性和方法。
function(x,y){
    return {x, y}
}
//上面的寫法等同於:

function(x,y){
    return {x: x, y: y}
}



//對象的方法也可使用簡潔表示法:
var o = {
    method(){
        return "Hello!";
    }
};
//等同於:
var o = {
    method: function(){
        return "Hello!";
    }
}
</script>
View Code

二、Object.assign()

  • Object.assign方法用來將源對象(source)的全部可枚舉屬性複製到目標對象(target)。它至少須要兩個對象做爲參數,第一個參數是目標對象,第二個參數是源對象。
  • 參數必須都是對象,不然拋出TypeError錯誤。
  • Object.assjgn只複製自身屬性,不可枚舉屬性(enumerable爲false)和繼承的屬性不會被複制。
var x = {name: "Q1mi", age: 18};
var y = x;
var z = Object.assign({}, x);
x.age = 20;

x.age  // 20

y.age  // 20

z.age  // 18
View Code
<script type="text/javascript">
     
    // 字面量方式建立對象
    var person = {
        name:"alex",
        age: 20,
        fav:function () {
            console.log('喜歡AV');
            // this指的是當前的對象
            console.log(this.age);
        }
    };
    person.fav();       
 
    // es6中對象的單體模式,爲了解決箭頭函數this指向的問題 推出來一種寫法
    var person = {
        name:"alex",
        age: 20,
        fav(){
        // this指的是當前的對象,即便用它的對象 person對象,和普通函數同樣的效果
            console.log(this);
            console.log(arguments);
        }
    };
    person.fav('21312');
 
     
    // JavaScript 語言中,生成實例對象的傳統方法是經過構造函數。
    function Person(name,age){
        this.name = name;
        this.age = age;
    }
 
    Person.prototype.showName = function(){
        alert(this.name);
    };
 
    // 使用new關機字來建立對象
    var p = new Person('alex',19);
    p.showName()
 
 
    // ES6 提供了更接近傳統語言的寫法,引入了 Class(類)這個概念,做爲對象的模板。經過class關鍵字,能夠定義類。
    class Person{
        // 構造器  當你建立實例以後 constructor()方法會馬上調用 一般這個方法初始化對象的屬性
        // 這就是構造方法,而this關鍵字則表明實例對象。
        constructor(name,age){
            this.name = name;
            this.age = age;
        }  
        //方法之間不須要逗號分隔,加了會報錯。
        showName(){
            alert(this.name)
        }
    };
 
    var p2 = new Person('張三',20);
    p2.showName();
     
</script>
對象
<script>
//ES5的構造對象的方式 使用構造函數來創造。構造函數惟一的不一樣是函數名首字母要大寫。
function Point(x, y){
    this.x = x;
    this.y = y;
}

// 給父級綁定方法
Point.prototype.toSting = function(){
    return '(' + this.x + ',' + this.y + ')';
};

var p = new Point(10, 20);
console.log(p.x);  //10
p.toSting();

// 繼承
function ColorPoint(x, y, color){
    Point.call(this, x, y);
    this.color = color;
}
// 繼承父類的方法
ColorPoint.prototype = Object.create(Point.prototype);
// 修復 constructor
ColorPoint.prototype.constructor = Point;
// 擴展方法
ColorPoint.prototype.showColor = function(){
    console.log('My color is ' + this.color);
};

var cp = new ColorPoint(10, 20, "red");
console.log(cp.x);   // 10
console.log(cp.toSting());  //(10,20)
cp.showColor();    //My color is red



//ES6 使用Class構造對象的方式:
class Point{
    constructor(x, y){
        this.x = x;
        this.y = y;
    }  // 不要加逗號
    toSting(){
        return `(${this.x}, ${this.y})`;
    }
}

var p = new Point(10, 20);
console.log(p.x);
p.toSting();

class ColorPoint extends Point{
    constructor(x, y, color){
        super(x, y);  // 調用父類的constructor(x, y)
        this.color = color;
    }  // 不要加逗號
    showColor(){
        console.log('My color is ' + this.color);
    }
}

var cp = new ColorPoint(10, 20, "red");
console.log(cp.x);
cp.toSting();
cp.showColor()
</script>
View Code

5、類

ES6 引入了關鍵字class來定義一個類,constructor是構造方法,this表明實例對象。前端

類之間經過extends繼承,繼承父類的全部屬性和方法。java

super關鍵字,它代指父類的this對象,子類必須在constructor中調用super()方法,es6

不然新建實例時會報錯,由於子類沒有本身的this對象。調用super()獲得this,才能進行修改。編程

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<script type= "text/javascript" >
     class Animal{
         constructor(){
             this .type = "animal"
         }
         says(say){
             console.log( this .type + "says" + say )
         }
     }
     let animal = new Animal()
     animal.says( "hello" )
 
     class Dog extends Animal{
         constructor(){
             super ();
             this .type = "dog" ;
         }
     }
     let dog = new Dog()
     dog.says( "hi" )
</script>

6、import和export

import 導入模塊、export導出模塊數組

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// main.js
// 導出多個聲明
export var name = "alex"
export var age = "18"
export function aa() {
     return 1
}
// 批量導出
export {name, age, aa}
  
// test.js
import {name, age, aa} from "./main"
console.log(name)
console.log(age)
console.log(aa())
// 整個模塊導入 把模塊當作一個對象
// 該模塊下全部的導出都會做爲對象的屬性存在
import * as obj from "./main"
console.log(obj.name)
console.log(obj.age)
console.log(obj.aa())      
 
// 一個模塊只能有一個默認導出
// 對於默認導出 導入的時候名字能夠不同
// main.js
var app = new Vue({
 
});
export default app
// test.js
// import app from "./main"
import my_app from "./main"

7、解構賦值

ES6容許按照必定的模式,從數組或對象中提取值,對變量進行賦值,這種方式被稱爲解構賦值。promise

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<script type= "text/javascript" >
const people = {
     name: "tom" ,
     age: 18,
};
const person = [ "rose" , "jack" ]
 
const { name, age } = people
console.log(name)  //tom
console.log(age)   //18
const [name1, name2] = person
console.log(name1)  //rose
console.log(name2)  //jack
</script>

8、字符串函數

  • 在此以前,JavaScript中只有str.indexOf(char)方法可用來肯定一個字符串是否包含在另外一個字符串中。
  • ES6中又提供了3種新方法:
  • includes():返回布爾值,表示是否找到了參數字符串。
  • stratsWith():返回布爾值,表示參數字符串是否在源字符串的開始位置。
  • endsWith():返回布爾值,表示參數字符串是否在源字符串的結尾位置。
<script>
var s = "Hello world!";

s.includes("o");  // true
s.startsWith("Hello");  // true
s.endsWith("!");  // true

//這三個方法都支持第2個參數,表示開始匹配的位置。
s.includes("o", 8);  // false
s.startsWith("world", 6);  // true
s.endsWith("Hello", 5);  // true

</script>
View Code

9、Promise

  • Promise 是異步編程的一種解決方案,比傳統的解決方案(回調函數和事件)更合理、更強大。它由社區最先提出和實現,ES6 將其寫進了語言標準,統一了用法,原生提供了Promise對象。
  • 使用Promise的優點是有了Promise對象,就能夠將異步操做以同步操做的流程表達出來,避免了層層嵌套的回調函數。此外,Promise對象提供統一的接口,使得控制異步操做更加容易。
  • Promise構造函數接受一個函數做爲參數,該函數的兩個參數分別是resolvereject。它們是兩個函數,由 JavaScript 引擎提供,不用本身部署。
  • Promise實例生成之後,能夠用then方法分別指定resolved狀態和rejected狀態的回調函數。
  • then方法能夠接受兩個回調函數做爲參數。第一個回調函數是Promise對象的狀態變爲resolved時調用,第二個回調函數是Promise對象的狀態變爲rejected時調用。其中,第二個函數是可選的,不必定要提供。這兩個函數都接受Promise對象傳出的值做爲參數。
  • 其實Promise.prototype.catch方法是.then(null, rejection)的別名,用於指定發生錯誤時的回調函數。
const promiseObj = new Promise(function(resolve, reject) {
  // ... some code

  if (/* 異步操做成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

<script>
promiseObj.then(function(value) {
  // success
}, function(error) {
  // failure
});

//還能夠將上面的代碼寫成下面這種方式:
promiseObj
.then(function(value) {
  // success
})
.catch(function(error) {
  // failure
});
</script>
View Code
相關文章
相關標籤/搜索