javascript - Angular 2 : Ts: Nested functions

标签 javascript angular types

我正在开发一个函数,有人可以就如何指定函数之外的函数提供建议吗? 在 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

https://plnkr.co/edit/XCHsu19UhR9wWxz4VLOx?p=preview

最佳答案

这正是您应该通过 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/

相关文章:

angular - 如何检测 Swiper 中幻灯片的点击?

javascript - Angular 2 *ngIf true -> 渲染按钮

javascript - 如何在另一个DIV中显示一个DIV的内容

Javascript innerHTML 更改不起作用

javascript - Concat RTL 字符串与 javascript 中的 LTR 字符串

sql-server - 为什么这个 COALESCE 语句中会发生这种隐式类型转换?

haskell - 在 Haskell 中使用 `print' 没有产生 (Show a0) 的实例

javascript - 在 FTL 中向我的模型发送一个 javascript var

java - 如何根据后端的 ANTLR 语法在前端检查用户输入是否有效?

typescript - 在 Typescript 中递归泛型?