ES6中的箭头函数和扩展
songStar0904 opened this issue · comments
songStar commented
箭头函数表达式的语法比函数表达式更短, 并且不绑定自己的this, arguments, super 或 new.target
。 这些函数表达式最适合用于非方法函数, 并且他们不能用作构造函数。
- 更短函数
let materials = ['foo', 'bar', 'baz'];
materials.map(function(material) {
return material.length;
}); // [3, 3, 3]
materials.map(material => material.length); // [3, 3, 3]
- 不绑定this
- 与严格模式的关系
鉴于this
是此法层面上的, 严格模式中与this
相关的关泽都被忽略。
var f = () => {'user strict'; return this};
f() === window; // true
var b = function() {
'use strict';
return this;
}
b(); // undefined
- 通过call / apply 调用
由于this
已经在此法层面完成了绑定, 通过call() / apply()
方法调用一个函数时, 只是传入的参数而已, 对this
并没有影响。
var adder = {
base: 1,
add: function(a) {
var f = v => v + this.base;
return f(a);
},
addThruCall: function(a) {
var f = v => v + this.base;
var b = {
base: 2
};
return f.call(b, a);
}
};
console.log(adder.add(1)); // 2
console.log(adder.addThruCall(1)); // 2 不是3
- 不绑定arguments
箭头函数不绑定Arguments
对象。 因此, 参数只是在封闭范围内引用相同的名称。
var arguments = 42;
var arr = () => arguments;
arr(); // 42
function foo() {
var f = i => arguments[0] + i;
return f(2);
}
foo(1); // 3(1+2)
function foo() {
var f = function(i) {
return arguments[0] + i;
}
return f(2);
}
foo(1); // 4(2+2)
在大多数情况下, 使用剩余参数是使用arguments对象的好选择。
function foo() {
var f = (...args) => args[0];
return f(2);
}
foo(1); // 2
- 像方法一样使用箭头函数
如上所述,箭头函数表达式对非方法函数是最合适的。让我们看看当我们试着把它们作为方法时发生了什么。
var obj = {
i: 10,
b: () => console.log(this.i, this),
c: function() {
console.log(this.i, this)
}
}
obj.b(); // undefined windows (严格模式下 undefined)
obj.c(); // 10, Object {...}
箭头函数没有定义this绑定。另一个涉及Object.defineProperty()的示例:
var obj = {
a: 10
};
Object.defineProperty(obj, 'b', {
get: () => {
console.log(this.a, this);
return this.a + 10;
// undefined windows
}
});
- 使用new操作符
箭头函数不能用作构造器, 和new
一起使用会抛出错误
var Foo = () => {};
var foo = new Foo(); // TypeError: Foo is not a constructor
- 使用prototype属性
箭头函数没有prototype属性。
var Foo = () => {};
console.log(Foo.prototype); // undefined
- 使用 yield 关键字
yield 关键字通常不能在箭头函数中使用(除非是嵌套在允许使用的函数内)。因此,箭头函数不能用作生成器。