defineProperty:...,
getPrototypeOf:...,
setPrototypeOf:...,
enumerate:...,
ownKeys:...,
preventExtensions:...,
isExtensible:...
}
Symbols
對象其實是鍵值對的集合,而鍵通常來說是字符串。而現在除了字符串外,我們還可以用symbol這種值來做為對象的鍵。Symbol是一種基本類型,像數字,字符串還有布爾一樣,它不是一個對象。Symbol 通過調用symbol函數產生,它接收一個可選的名字參數,該函數返回的symbol是唯一的。之後就可以用這個返回值做為對象的鍵了。Symbol還可以用來創建私有屬性,外部無法直接訪問由symbol做為鍵的屬性值。
var MyClass = (function() {
// module scoped symbol
var key = Symbol("key");
function MyClass(privateData) {
this[key] = privateData;
}
MyClass.prototype = {
doStuff: function() {
... this[key] ...
}
};
return MyClass;
})();
var c = new MyClass("hello")
c["key"] === undefined
Math + Number + String + Array + Object API
對Math,Number,String還有Object等添加了許多新的API。
Number.EPSILON
Number.isInteger(Infinity) // false
Number.isNaN("NaN") // false
Math.acosh(3) // 1.762747174039086
Math.hypot(3, 4) // 5
Math.imul(Math.pow(2, 32) - 1, Math.pow(2, 32) - 2) // 2
"abcde".includes("cd") // true
"abc".repeat(3) // "abcabcabc"
Array.from(document.querySelectorAll('*')) // Returns a real Array
Array.of(1, 2, 3) // Similar to new Array(...), but without special one-arg behavior
[0, 0, 0].fill(7, 1) // [0,7,7]
[1, 2, 3].find(x => x == 3) // 3
[1, 2, 3].findIndex(x => x == 2) // 1
[1, 2, 3, 4, 5].copyWithin(3, 0) // [1, 2, 3, 1, 2]
["a", "b", "c"].entries() // iterator [0, "a"], [1,"b"], [2,"c"]
["a", "b", "c"].keys() // iterator 0, 1, 2
["a", "b", "c"].values() // iterator "a", "b", "c"
Object.assign(Point, { origin: new Point(0,0) })
更多信息見文尾的ES6 API擴展的鏈接。
二進制和八進制
ES6中新增了兩種數字文字:binary (b) 和 octal (o),分別用前綴0b和0o表示。
0b111110111 === 503 // true
0o767 === 503 // true
Promises
Promises是處理異步操作的一種模式。當你發起一個異步請求,並綁定了.when(), .done()等事件處理程序時,其實就是在應用promise模式。
function timeout(duration = 0) {
return new Promise((resolve, reject) => {
setTimeout(resolve, duration);
})
}
var p = timeout(1000).then(() => {
return timeout(2000);
}).then(() => {
throw new Error("hmm");
}).catch(err => {
return Promise.all([timeout(100), timeout(200)]);
})
閱讀更多 奔跑的經理 的文章