ES6入門

1.利用gulp+babel轉es6   http://www.cnblogs.com/sanxiaoshan/p/6850342.html
javascript


2.目錄結構css


3.index.htmlhtml

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div style="margin-top: 20px">
    <input type="button" class="button" value="按鈕1">
    <input type="button" class="button" value="按鈕2">
    <input type="button" class="button" value="按鈕3">
    <input type="button" class="button" value="按鈕4">
    <input type="button" class="button" value="按鈕5">
</div>
<div id="result"></div>
<script src="es6/index.js" ></script>
</body>
</html>

4.gulpfile.js

var gulp = require('gulp');
var babel = require('gulp-babel');

gulp.task('default', function () {
   return gulp.src('es6/*.js')
       .pipe(babel({
          presets:['es2015']
       }))
       .pipe(gulp.dest('build'))
   console.log('ok');
});

5.index.js

//let爲JavaScript新增了塊級做用域。用它所聲明的變量,只在let命令所在的代碼塊內有效
//----------------------------es5---------------------------------
var name_es5 = 'zach'

while (true) {
    var name_es5 = 'obama'
    console.log(name_es5)  //obama
    break
}

console.log(name_es5)  //obama
//----------------------------es5---------------------------------

//----------------------------es6---------------------------------
let name_es6 = 'zach'

while (true) {
    let name_es6 = 'obama'
    console.log(name_es6)  //obama
    break
}

console.log(name_es6)  //zach
//----------------------------es6---------------------------------

//----------------------------es5---------------------------------
var add_the_handlers_new = function (nodes) {
    var helper = function (i) {
        return function (e) {
            alert(i);
        }
    }
    var i;
    for (i = 0; i < nodes.length; i++) {
        nodes[i].onclick = helper(i + 1);
    }
};

add_the_handlers_new($('.button'));
//----------------------------es5---------------------------------

//----------------------------es6---------------------------------
var add_the_handlers_new_es6 = function (nodes) {
    for (let i = 0; i < nodes.length; i++) {
        $(nodes[i]).click(function () {
            console.log(i);
        });
    }
};

add_the_handlers_new_es6($('.button'));
//----------------------------es6---------------------------------

//const也用來聲明變量,可是聲明的是常量。一旦聲明,常量的值就不能改變。
//const有一個很好的應用場景,就是當咱們引用第三方庫的時聲明的變量,用const來聲明能夠避免將來不當心重命名而致使出現bug
const PI = Math.PI

//PI = 23 //Module build failed: SyntaxError: /es6/app.js: "PI" is read-only

//const monent = require('moment')

//class, extends, super
//class定義了一個「類」,constructor內定義的方法和屬性是實例對象本身的,而constructor外定義的方法和屬性則是全部實例對象能夠共享的
//extends關鍵字實現繼承
//super關鍵字,它指代父類的實例(即父類的this對象)。子類必須在constructor方法中調用super方法,不然新建實例時會報錯。這是由於子
//類沒有本身的this對象,而是繼承父類的this對象,而後對其進行加工。若是不調用super方法,子類就得不到this對象。

class Animal {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        console.log(this.type + ' says ' + say)
    }
}

let animal = new Animal()
animal.says('hello') //animal says hello

class Cat extends Animal {
    constructor(){
        super()
        this.type = 'cat'
    }
}

let cat = new Cat()
cat.says('hello') //cat says hello


//當咱們使用箭頭函數時,函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。
//並非由於箭頭函數內部有綁定this的機制,實際緣由是箭頭函數根本沒有本身的this,它的this是繼承外面的,所以內部的this就是外層代碼塊的this。
class Animal2 {
    constructor(){
        this.type = 'animal'
    }
    says(say){
        setTimeout( () => {
            console.log(this.type + ' says ' + say)
        }, 1000)
    }
}
var animal2 = new Animal2()
animal2.says('hi')  //animal says hi

var basket = {
  count : '10',
    onSale: '6'
};

//template string
//這個東西能夠用在咱們要插入大段的html內容到文檔中。
$("#result").append(`
  There are <b>${basket.count}</b> items
   in your basket, <em>${basket.onSale}</em>
  are on sale!
`);

//從數組和對象中提取值,對變量進行賦值,這被稱爲解構(Destructuring)。
let mycat = 'ken'
let dog = 'lili'
let zoo = {mycat, dog}
console.log(zoo)  //Object {mycat: "ken", dog: "lili"}

let mydog = {type: 'animal', many: 2}
let { type, many} = mydog
console.log(type, many)   //animal 2


//default很簡單,意思就是默認值。你們能夠看下面的例子,調用animal()方法時忘了傳參數,傳統的作法就是加上這一句type = type || 'cat' 來指定默認值
function myanimal(type = 'cat'){
    console.log(type)
}
myanimal()

//rest語法也很簡單,直接看例子
function animals(...types){
    console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]

6.編譯後的index.js

'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }

function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

//let爲JavaScript新增了塊級做用域。用它所聲明的變量,只在let命令所在的代碼塊內有效
//----------------------------es5---------------------------------
var name_es5 = 'zach';

while (true) {
    var name_es5 = 'obama';
    console.log(name_es5); //obama
    break;
}

console.log(name_es5); //obama
//----------------------------es5---------------------------------

//----------------------------es6---------------------------------
var name_es6 = 'zach';

while (true) {
    var _name_es = 'obama';
    console.log(_name_es); //obama
    break;
}

console.log(name_es6); //zach
//----------------------------es6---------------------------------

//----------------------------es5---------------------------------
var add_the_handlers_new = function add_the_handlers_new(nodes) {
    var helper = function helper(i) {
        return function (e) {
            alert(i);
        };
    };
    var i;
    for (i = 0; i < nodes.length; i++) {
        nodes[i].onclick = helper(i + 1);
    }
};

add_the_handlers_new($('.button'));
//----------------------------es5---------------------------------

//----------------------------es6---------------------------------
var add_the_handlers_new_es6 = function add_the_handlers_new_es6(nodes) {
    var _loop = function _loop(i) {
        $(nodes[i]).click(function () {
            console.log(i);
        });
    };

    for (var i = 0; i < nodes.length; i++) {
        _loop(i);
    }
};

add_the_handlers_new_es6($('.button'));
//----------------------------es6---------------------------------

//const也用來聲明變量,可是聲明的是常量。一旦聲明,常量的值就不能改變。
//const有一個很好的應用場景,就是當咱們引用第三方庫的時聲明的變量,用const來聲明能夠避免將來不當心重命名而致使出現bug
var PI = Math.PI;

//PI = 23 //Module build failed: SyntaxError: /es6/app.js: "PI" is read-only

//const monent = require('moment')

//class, extends, super
//class定義了一個「類」,constructor內定義的方法和屬性是實例對象本身的,而constructor外定義的方法和屬性則是全部實例對象能夠共享的
//extends關鍵字實現繼承
//super關鍵字,它指代父類的實例(即父類的this對象)。子類必須在constructor方法中調用super方法,不然新建實例時會報錯。這是由於子
//類沒有本身的this對象,而是繼承父類的this對象,而後對其進行加工。若是不調用super方法,子類就得不到this對象。

var Animal = function () {
    function Animal() {
        _classCallCheck(this, Animal);

        this.type = 'animal';
    }

    _createClass(Animal, [{
        key: 'says',
        value: function says(say) {
            console.log(this.type + ' says ' + say);
        }
    }]);

    return Animal;
}();

var animal = new Animal();
animal.says('hello'); //animal says hello

var Cat = function (_Animal) {
    _inherits(Cat, _Animal);

    function Cat() {
        _classCallCheck(this, Cat);

        var _this = _possibleConstructorReturn(this, (Cat.__proto__ || Object.getPrototypeOf(Cat)).call(this));

        _this.type = 'cat';
        return _this;
    }

    return Cat;
}(Animal);

var cat = new Cat();
cat.says('hello'); //cat says hello


//當咱們使用箭頭函數時,函數體內的this對象,就是定義時所在的對象,而不是使用時所在的對象。
//並非由於箭頭函數內部有綁定this的機制,實際緣由是箭頭函數根本沒有本身的this,它的this是繼承外面的,所以內部的this就是外層代碼塊的this。

var Animal2 = function () {
    function Animal2() {
        _classCallCheck(this, Animal2);

        this.type = 'animal';
    }

    _createClass(Animal2, [{
        key: 'says',
        value: function says(say) {
            var _this2 = this;

            setTimeout(function () {
                console.log(_this2.type + ' says ' + say);
            }, 1000);
        }
    }]);

    return Animal2;
}();

var animal2 = new Animal2();
animal2.says('hi'); //animal says hi

var basket = {
    count: '10',
    onSale: '6'
};

//template string
//這個東西能夠用在咱們要插入大段的html內容到文檔中。
$("#result").append('\n  There are <b>' + basket.count + '</b> items\n   in your basket, <em>' + basket.onSale + '</em>\n  are on sale!\n');

//從數組和對象中提取值,對變量進行賦值,這被稱爲解構(Destructuring)。
var mycat = 'ken';
var dog = 'lili';
var zoo = { mycat: mycat, dog: dog };
console.log(zoo); //Object {mycat: "ken", dog: "lili"}

var mydog = { type: 'animal', many: 2 };
var type = mydog.type,
    many = mydog.many;

console.log(type, many); //animal 2


//default很簡單,意思就是默認值。你們能夠看下面的例子,調用animal()方法時忘了傳參數,傳統的作法就是加上這一句type = type || 'cat' 來指定默認值
function myanimal() {
    var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'cat';

    console.log(type);
}
myanimal();

//rest語法也很簡單,直接看例子
function animals() {
    for (var _len = arguments.length, types = Array(_len), _key = 0; _key < _len; _key++) {
        types[_key] = arguments[_key];
    }

    console.log(types);
}
animals('cat', 'dog', 'fish'); //["cat", "dog", "fish"]

7.



8.參考連接:http://www.javashuo.com/article/p-eueyuluo-gn.html
java

相關文章
相關標籤/搜索