规范问题如果在用箭头函数替换函数声明/表达式后发现有关问题的问题,请将其作为此副本的副本关闭.
ES2015中的箭头功能提供了更简洁的语法.我现在可以用箭头功能替换所有函数声明/表达式吗?我需要注意什么?
例子:
构造函数
function User(name) {
this.name = name;
}
// vs
const User = name => {
this.name = name;
};
Run Code Online (Sandbox Code Playgroud)
原型方法
User.prototype.getName = function() {
return this.name;
};
// vs
User.prototype.getName = () => this.name;
Run Code Online (Sandbox Code Playgroud)
对象(文字)方法
const obj = {
getName: function() {
// ...
}
};
// vs
const obj = {
getName: () => {
// ...
}
};
Run Code Online (Sandbox Code Playgroud)
回调
setTimeout(function() {
// ...
}, 500);
// vs
setTimeout(() => {
// ...
}, …Run Code Online (Sandbox Code Playgroud) 据我了解,这不起作用(这是一个人为的示例 - 请参阅 RxJS 了解我实际运行的内容):
function Foo() {
this.name = 'Johnny Cash'
}
Foo.prototype.who = () => {
console.log(this.name) // undefined
};
var foo = new Foo();
foo.who()
Run Code Online (Sandbox Code Playgroud)
因为this没有正确的范围。然而,RxJS 文档上的这个页面(最后 2 个底部示例)使用了它。他们如何运行这段代码?
RxJS页面上的代码是否错误?或者我是否需要运行某种 Babel 插件(我已经尝试通过 babel-require 和 babel-polyfill 运行,效果相同)
这段代码:
'use strict'
function Ob() {}
Ob.prototype.add = () => {
this.inc()
}
Ob.prototype.inc = () => {
console.log(' Inc called ');
}
module.exports = new Ob();
Run Code Online (Sandbox Code Playgroud)
由此代码使用:
'use strict'
const ob = require('./ob')
ob.add();
Run Code Online (Sandbox Code Playgroud)
调用梯形图时,我收到此错误:
this.inc is not a function
当我将第一个代码段更改为:
'use strict'
function Ob() {}
Ob.prototype.add = function() {
this.inc();
}
Ob.prototype.inc = function() {
console.log(' Inc called ');
}
module.exports = new Ob();
Run Code Online (Sandbox Code Playgroud)
一切都很好,我得到:
Inc called
为什么第一个版本会抛出?
更新:如何使用箭头功能使其工作?