[ES6] Arrow Function 的 this 陷井

Peter Chang
OrienteBar
Published in
1 min readDec 2, 2016

Arrow Function 的方便性使 Javascript 定義 Function 就像燃點香煙一樣快捷,但方便的同時帶著幾種容易出現的陷井。

ES6 新增很多幫助開發和 OOP 的 Function,其中的 Arrow functions, Classes 更是不能錯過。新 Feature 常常意味著不穩定性,所以使用 Arrow Function 時要小心幾個情景。
( ES6的10個 cool feature )

1- Object prototype function

function MyCat(name) {  
this.catName = name;
}
MyCat.prototype.sayCatName = () => {
console.log(this === window); // => true
return this.catName;
};
var cat = new MyCat('Mew');
cat.sayCatName(); // => undefined

使用舊的方法

function MyCat(name) {  
this.catName = name;
}
MyCat.prototype.sayCatName = function() {
console.log(this === cat); // => true
return this.catName;
};
var cat = new MyCat('Mew');
cat.sayCatName(); // => 'Mew'

2- Object constructor

var Message = (text) => {  
this.text = text;
};
// Throws "TypeError: Message is not a constructor"
var helloMessage = new Message('Hello World!');
var Message = function(text) {
this.text = text;
};
var helloMessage = new Message('Hello World!');
console.log(helloMessage.text); // => 'Hello World!'

from:

https://github.com/lukehoban/es6features#introduction

https://rainsoft.io/when-not-to-use-arrow-functions-in-javascript/

--

--