本系列是在平時閱讀、學習、實際項目中有關於es6中的新特性、用發的簡單總結,目的是記錄以備往後溫習;本系列預計包含let/const、箭頭函數、解構、經常使用新增方法、Symbol、Set&Map、Proxy、reflect、Class、Module、Iterator、Promise、Generator、async/await。。。es6
箭頭函數顧名思義就是帶箭頭的函數,^-^,其實想表達的是箭頭函數本質仍是函數,那箭頭函數和es5的函數有什麼區別呢?async
var obj = { age: 1, say: function() { setTimeout(function() { console.log(this, this.age); // window undefined }, 0); }, } var obj1 = { age: 1, say: function() { setTimeout(() => { console.log(this, this.age); // obj1 1 }, 0); } };
這裏能夠看出箭頭函數中訪問的this其實是其父級做用域中的this,箭頭函數自己的this是不存在的,這樣就至關於箭頭函數的this是在聲明的時候就肯定了(由於至關於做用域嘛),這個特性是頗有用的函數
var handler = { id: '111', doSomething: function(e) { console.log(e); }, init: function() { document.addEventListener('click', (event) => { // 這裏綁定事件,函數this就能夠訪問到handler的方法doSomething this.doSomething(event); }, false); } } handler.init();
var Person = (name) => { // Uncaught TypeError: Person is not a constructor this.name = name; } var person = new Person('Jack');
這個特性很容易測試,若是上一條明白的話也很容易理解: 箭頭函數壓根就沒有this,固然不能做爲構造函數(若是明白構造函數new的過程的話,插一句: new的過程其實就是建立一個對象,將this指向該對象,而後執行代碼初始化這個對象,最後返回)學習
var foo = (val) => { console.log(arguments); // Uncaught ReferenceError: arguments is not defined }; foo();
這個特性也很好測試,可是實在要使用arguments對象要怎麼辦呢?咱們可使用es6的另外一個新特性rest參數,完美替代測試
var foo = (...args) => { console.log(args); // [1, 2, 3] }; foo(1, 2, 3);
箭頭函數不適用的場景(或者不建議使用的場景)this
這裏說的不適用有些是壓根不能用,有些是若是使用了箭頭函數可能會產生意想不到的結果es5
var obj = { a: () => { console.log(this); // window } };
做爲對象的屬性時,this的指向則再也不是對象自己了,這就形成了意想不到的結果spa
function Person(name) { this.name = name; } Person.prototype.say = function() { console.log(this); // 指向實例 }; Person.prototype.bark = () => { console.log(this); // window }; var pe = new Person('Jack'); pe.say(); // {name: 'Jack'} pe.bark(); // window
從例子中咱們看到了,箭頭函數做爲原型方法時,this指向出乎了咱們的意料prototype
document.addEventListener('click', () => { console.log(this); // window }, false); document.addEventListener('click', function() { console.log(this); // #document對象 }, false); // 通常狀況,咱們綁定事件處理函數時但願函數內部的this指向綁定的Dom對象,可是若是使用了箭頭函數,則this則會出乎咱們的意料