1. 程式人生 > >es6的基本用法

es6的基本用法

1. let和const

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
let:
  //區域性作用域
var a = []; for (let i = 0; i < 10; i++){ a[i] = function () { console.log(i) } } a[
2]() //2
   a[5]() //5
  //不會存在變數提升
 
 console.log(a); //undefined
  {
  var a = 1;
  var a = 10
}
  console.log(a); //10
  //變數不能重複宣告
  
let a = 1;
  let a = 10;
  console.log(a); //10


// const:區域性作用域,不會存在變數提升,不能重複宣告,只宣告常量,不可變的量
</script> </body> </html>

 

2. es6的箭頭函式

<!DOCTYPE html>
<html lang
="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> function add(x) { return x }; console.log(add(1)); //1 let add1 = function (x) { return x }; console.log(add1(10
)); //10 let add2 = (x) => x; console.log(add2(20)); //20 </script> </body> </html>

 

3. es6的物件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script>
    let person1 = {
        methods:{
            fav:function () {
            }
        },
        name:"ritian",
        age:30,
        fav:function () {
            console.log(this); //this指當前的person1物件
            console.log(this.name);
            console.log(this.age);
        }
    };
    person1.fav();
    

    let person2 = {
        name:"ritian2",
        age:30,
        fav:() => {
            console.log(this); //this指定義person的父級物件(window)
            console.log(this.name);
        }
    };
    person2.fav();


    let person3 = {
        name:"ritian",
        fav(){
            console.log(this); //當前this,即person3
        }
    };
    person3.fav()
</script>
</body>
</html>

 

4. es6的類

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>4</title>
</head>
<body>
<script>
    function Vue(name,age) {
        this.name = name;
        this.age = age;
        console.log(this.name); //ritian
        console.log(this.age); //18
    }


    //基於原型給物件宣告方法
    Vue.prototype.showName = function(){
      console.log(this.name);
    };
    Vue("ritian",18);

    class Person{
        constructor(name="ritian",age=18){
            this.name = name;
            this.age = age;
        }
        showname(){
            console.log(this.name);
        }
        showage(){
            console.log(this.age);
        }
    }

    let V = new Person();
    V.showname(); //ritian
    V.showage(); //18
</script>
</body>
</html>