Ecmascript6新特性二

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)]);

})


分享到:


相關文章: