# [OHIF-Viewers]医疗数字阅片-医学影像-ES6箭头函数(=>)

https://www.liaoxuefeng.com/wiki/1022910821149312/1031549578462080

## 箭头函数

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

x => x * x

function (x) {
return x * x;
}

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

posted @ 2020-07-08 16:35  landv  阅读(175)  评论(0编辑  收藏  举报