* [9.1](https://github.com/yuche/javascript#9.1)?總是使用?`class`。避免直接操作?`prototype`?。
> 為什么? 因為?`class`?語法更為簡潔更易讀。
~~~
// bad
function Queue(contents = []) {
this._queue = [...contents];
}
Queue.prototype.pop = function() {
const value = this._queue[0];
this._queue.splice(0, 1);
return value;
}
// good
class Queue {
constructor(contents = []) {
this._queue = [...contents];
}
pop() {
const value = this._queue[0];
this._queue.splice(0, 1);
return value;
}
}
~~~
* [9.2](https://github.com/yuche/javascript#9.2)?使用?`extends`?繼承。
> 為什么?因為?`extends`?是一個內建的原型繼承方法并且不會破壞?`instanceof`。
~~~
// bad
const inherits = require('inherits');
function PeekableQueue(contents) {
Queue.apply(this, contents);
}
inherits(PeekableQueue, Queue);
PeekableQueue.prototype.peek = function() {
return this._queue[0];
}
// good
class PeekableQueue extends Queue {
peek() {
return this._queue[0];
}
}
~~~
* [9.3](https://github.com/yuche/javascript#9.3)?方法可以返回?`this`?來幫助鏈式調用。
~~~
// bad
Jedi.prototype.jump = function() {
this.jumping = true;
return true;
};
Jedi.prototype.setHeight = function(height) {
this.height = height;
};
const luke = new Jedi();
luke.jump(); // => true
luke.setHeight(20); // => undefined
// good
class Jedi {
jump() {
this.jumping = true;
return this;
}
setHeight(height) {
this.height = height;
return this;
}
}
const luke = new Jedi();
luke.jump()
.setHeight(20);
~~~
* [9.4](https://github.com/yuche/javascript#9.4)?可以寫一個自定義的?`toString()`?方法,但要確保它能正常運行并且不會引起副作用。
~~~
class Jedi {
constructor(options = {}) {
this.name = options.name || 'no name';
}
getName() {
return this.name;
}
toString() {
return `Jedi - ${this.getName()}`;
}
}
~~~
- 關于
- 1. 類型
- 2. 引用
- 3. 對象
- 4. 數組
- 5. 解構
- 6. 字符串
- 7. 函數
- 8. 箭頭函數
- 9. 構造函數
- 10. 模塊
- 11. Iterators & Generators
- 12. 屬性
- 13. 變量
- 14. 提升
- 15. 比較運算符 & 等號
- 16. 代碼塊
- 17. 注釋
- 18. 空白
- 19. 逗號
- 20. 分號
- 21. 類型轉換
- 22. 命名規則
- 23. 存取器
- 24. 事件
- 25. jQuery
- 26. ECMAScript 5 兼容性
- 27. ECMAScript 6 編碼規范
- 28. 測試
- 29. 性能
- 30. 資源
- 31. 使用人群
- 32. 翻譯
- 33. JavaScript 編碼規范說明
- 34. 一起來討論Javascript
- 35. Contributors
- 36. License