我正在开发一个函数,有人可以就如何指定函数之外的函数提供建议吗? 在 if 语句中我想调用 otherfunction()。
@Injectable()
export class menuService {
constructor (){}
testing(){ console.log('something')}
loadwidget(){
// not able to call this function
this.testing()
}
}
我得到的错误是“this.testing不是一个函数”
ERROR TypeError: this.testing is not a function
at Object.menuService.loadwidget (http://localhost:3000/main.bundle.js:755:14)
at Object.eval [as handleEvent] (ng:///AppModule/tbuttonsComponent.ngfactory.js:36:41)
at handleEvent (http://localhost:3000/vendor.dll.js:13146:138)
at callWithDebugContext (http://localhost:3000/vendor.dll.js:14354:42)
at Object.debugHandleEvent [as handleEvent] (http://localhost:3000/vendor.dll.js:13942:12)
at dispatchEvent (http://localhost:3000/vendor.dll.js:10121:21)
at http://localhost:3000/vendor.dll.js:10711:38
最佳答案
这正是您应该通过 this
关键字访问类中其他方法的方式。如果您完全按照编写的方式使用上面的类,那么问题是 variableName
未在 customfunction()
中的任何位置定义,因此会出错。因此,otherfunction()
中的 console.log()
语句永远没有机会运行。
编辑:我查看了您添加的 Plunker,结果发现这是一个范围问题。我更新了 menuService
类,使用箭头函数将 this
隐式绑定(bind)到 menuService
,第三个按钮开始按预期工作:
export class menuService {
constructor (){
// I moved this into the constructor and updated loadingwidget below
this.menu = [{
id: 1,
loadingwidget: () => { this.loadwidget(); },
}];
}
testing(){
console.log('something');
alert('something');
}
loadwidget(){
this.testing();
}
}
这是 Plunker 的工作版本:https://plnkr.co/edit/sF08cccRb2b0xkfTspVV?p=preview
关于javascript - Angular 2 : Ts: Nested functions,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44182018/