Ale*_*lex 0 node.js ecmascript-6
这段代码:
'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
为什么第一个版本会抛出?
更新:如何使用箭头功能使其工作?
它不能使用箭头函数,因为它们捕获this当前范围.在您的示例代码中
'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)
this这个代码运行时没有(好吧,有一个,但至少它不是构造函数创建的对象实例).本质上,此代码相当于:
'use strict'
const that = this;
function Ob() {}
Ob.prototype.add = function () {
that.inc()
}
Ob.prototype.inc = function () {
console.log(' Inc called ');
}
module.exports = new Ob();
Run Code Online (Sandbox Code Playgroud)
然后很明显,实际上没有任何功能that.inc().这就是为什么它不起作用.
如何使用箭头功能解决这个问题?好吧,我会说,不要在这里使用箭头功能,因为它完全没有意义,而且它们不仅仅是编写"普通"功能的另一种方式,它们略有不同.
如何解决这个问题?使用老式的function关键字,一切都会按预期工作:-)
| 归档时间: |
|
| 查看次数: |
31 次 |
| 最近记录: |