• Index

### 关于作者

#### 箭头函数

ES6标准新增了一种新的函数：Arrow Function（箭头函数）。

x => x * x


function (x) {
return x * x;
}


'use strict';
----
var fn = x => x * x;
----
console.log('你的浏览器支持ES6的Arrow Function!');


x => {
if (x > 0) {
return x * x;
}
else {
return - x * x;
}
}


// 两个参数:
(x, y) => x * x + y * y

// 无参数:
() => 3.14

// 可变参数:
(x, y, ...rest) => {
var i, sum = x + y;
for (i=0; i<rest.length; i++) {
sum += rest[i];
}
return sum;
}


// SyntaxError:
x => { foo: x }


// ok:
x => ({ foo: x })


### this

var obj = {
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
var fn = function () {
return new Date().getFullYear() - this.birth; // this指向window或undefined
};
return fn();
}
};


var obj = {
birth: 1990,
getAge: function () {
var b = this.birth; // 1990
var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
return fn();
}
};
obj.getAge(); // 25


var that = this;


var obj = {
birth: 1990,
getAge: function (year) {
var b = this.birth; // 1990
var fn = (y) => y - this.birth; // this.birth仍是1990
return fn.call({birth:2000}, year);
}
};
obj.getAge(2015); // 25


### 练习

'use strict'
var arr = [10, 20, 1, 2];
----
arr.sort((x, y) => {
???
});
console.log(arr); // [1, 2, 10, 20]