“this” undefined in side link function in Angular directive built with TypeScript

后端 未结 2 1406
Happy的楠姐
Happy的楠姐 2021-01-19 07:04

I\'m a relative newbie to both TypeScript and Angular so I\'m probably doing something very basic wrong here.

I\'m trying to create an abstract base class from which

相关标签:
2条回答
  • 2021-01-19 07:23

    In Angular directives it is unsafe to consider this a class instance because functions can have their own lexical this, and they actually have it.

    this is controller instance in controller (which may or may not be exposed on scope with 'controller as' syntax).

    this is DDO object in compile (so this is contextual here).

    this is undefined in linking functions (in strict mode).

    Use arrow functions if you're unsure about lexical this or want to override it:

    link = (...) => { ... };
    
    0 讨论(0)
  • 2021-01-19 07:33

    //tsc writes "var _this = this;" here, but this is undefined

    Two possible issues:

    • You should type _this in the debug console. This is because of the way the sourcemaps work at the moment : Chrome Typescript debugging references wrong 'this'

    • You are registering the directive with angular in a wrong way. Note that angular will not call new on foo if foo is used like .directive('foo',foo). Angular assumes its already a variable that has all the right stuff on it. Angular was not written with classes in mind (angular 1 is now fairly old).

    0 讨论(0)
提交回复
热议问题