var f = v => v*2; 借鑑思路與java8的lamada 表達式類似 ,寫匿名函數。
// 等價於
var f = function(v){
return v*2;
}
// 判斷偶數
var isEven = n => n % 2 == 0;
// 需要加 return
var = (a, b) => {
if(a >= b)
return a;
return b;
}
var isNumber= n => isNan(n);
1:箭頭函數
// ES6
function obj() {
setTimeout(()=>console.log(this.id), 20);
}
// ES5
function foo() {
var _this = this;
setTimeout(function () {
console.log(_this.id);
}, 20);
}
2:function* yield 迭代器
根據語法規範,yield 關鍵字用來暫停和繼續執行一個生成器函數。當外部調用生成器的 next() 方法時,yield 關鍵字右側的表達式纔會執行。
執行結果會轉化爲一個對象(包含兩個屬性, value 和 done),作爲 next() 方法的返回值。
對於 var foo = yield expression 語句,yield 左側變量 foo 的值將在下一次調用 next() 方法時獲得,並且等於調用時 next() 方法的參數。
function* 這種聲明方式(function關鍵字後跟一個星號)會定義一個生成器函數 (generator function),它返回一個 Generator 對象。
function* generator()
{
}
function* g1() {
yield 2
yield 3
}
function* g2() {
yield 1
yield g1()
yield* g1()
yield [4, 5]
yield* [6, 7]
}
const iterator = g2()
console.log(iterator.next()) // { value: 1, done: false }
console.log(iterator.next()) // { value: {}, done: false }
console.log(iterator.next()) // { value: 2, done: false }
console.log(iterator.next()) // { value: 3, done: false }
console.log(iterator.next()) // { value: [4, 5], done: false }
console.log(iterator.next()) // { value: 6, done: false }
console.log(iterator.next()) // { value: 7, done: false }
console.log(iterator.next()) // { value: undefined, done: true }
class 及繼承
//定義類
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
// 注意函數構造的方式
toString() {
return '(' + this.x + ', ' + this.y + ')';
}
}
var p1 = new Point(5, 5);
p1.toString(); //"(5, 5)"
typeof Point // function
p1.constructor == Point //tru
直接使用 class 關鍵字,constructor 作爲構造方法,函數可以直接 toString(){} 的方式。
但是,class 的本質仍然是函數,是構造函數的另外一種寫法。既然 class 的本質是函數,那麼必不可少的一些 proto,prototype 方法也是存在的。