仔細研究了es6的generator function + [co](https://github.com/tj/co "co")
才發現可以利用它來改善我們的程式寫法
讓程式的可讀性更高
先讓我們看看用Promise來撰寫非同步code的樣子
```javascript
let num = function (num) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num+1);
}, 500);
});
}
num(1).then((res) => {
return num(res);
}).then((res) => {
return num(res);
}).then((res) => {
// output
// promise result: 4
console.log(`promise result: ${res}`);
});
```
接下來讓我們來看看generator function + [co](https://github.com/tj/co "co")的寫法
```javascript
let num = function (num) {
return (callback) => {
setTimeout(function() {
callback(null, num+1);
}, 500);
}
}
co(function*() {
let num1 = yield num(1);
let num2 = yield num(num1);
let num3 = yield num(num2);
return num3;
}).then((res) => {
// output
// generator result: 4
console.log(`generator result: ${res}`);
});
```
[jsfiddle](https://jsfiddle.net/recca0120/eocp5h2c/ "jsfiddle範例")
2016年5月12日 星期四
2016年4月3日 星期日
es6如何拓增prototype
寫es6時要增加Object的prototype
已經和以往的寫法大為不同了
所以就來介紹一下方法吧
```js
// $.inArray 模擬 Array.includes
import $ from 'jquery';
if (!Array.prototype.includes) {
Object.defineProperty(Array.prototype, 'includes', {
value(...args) {
return $.inArray(...args, this) !== -1;
}
});
}
```
利用jQuery Promise模擬Native Promise
我們在寫es6時,會用到一些es6才有的函式或物件
但如果可以使用jQuery的一些內建函式來模擬的話
我們就不需要import 'babel-polyfill'
這樣產出來的javascript檔案就會少個90k左右
以下為程式碼
```js
'use strict';
import $ from 'jquery';
if (!window.Promise) {
class Promise {
constructor(callback) {
this.deferred = $.Deferred();
callback((o) => {
this.deferred.resolve(o);
}, (o) => {
this.deferred.reject(o);
});
this.promise = this.deferred.promise();
}
then(resolve, reject) {
this.promise.done(resolve);
this.promise.fail(reject);
return this;
}
catch(reject) {
this.promise.fail(reject);
return this;
}
}
window.Promise = Promise;
}
```
解決babel6 class extends 在 ie10 以下版本super無法呼叫 parent constructor
先直接看程式碼
```js
class A {
constructor() {
console.log('A');
}
}
class B extends A {
constructor() {
super();
}
}
new B();
```
這是一個很簡單物件繼承,預期console內輸出 "A"
實際做了測試之後發現在ie11, chrome, firefox都能正常輸出
但在ie9, ie10卻完全失效
後來查了原因後原來Object.getPrototypeOf在es5及es6的功能完全不同
才造成super失效
在github上已經有人提出兩種出解決方案
1.設定babel的plugins
```json
{
"presets": ["react", "es2015"],
"plugins": [
["transform-es2015-classes", { "loose": true }],
"transform-proto-to-assign"
]
}
```
2.修改Object.getPrototypeOf 來自[https://github.com/seznam/IMA.js-babel6-polyfill](https://github.com/seznam/IMA.js-babel6-polyfill "polyfill")
```js
(function() {
var testObject = {};
if (!(Object.setPrototypeOf || testObject.__proto__)) {
var nativeGetPrototypeOf = Object.getPrototypeOf;
Object.getPrototypeOf = function(object) {
if (object.__proto__) {
return object.__proto__;
} else {
return nativeGetPrototypeOf.call(Object, object);
}
}
}
})();
```
訂閱:
文章 (Atom)