构造函数不绑定类上下文的参数

时间:2016-08-01 04:01:36

标签: typescript

这是我的Greeter课程:

Uncaught TypeError: Cannot read property 'log' of undefined

此代码编译成功。但是当我运行它时,我得到错误:

IPHlpApi.Lib

发生了什么事?

更新 它也在typescript playground失败了。

2 个答案:

答案 0 :(得分:1)

在构造函数中,您不设置私有字段l
试试吧

constructor(l : Logger) {
  this.foo = "bar";
  this.l = l;
  this.l.log(this.foo);
}  

或(信用转到torazaburo

constructor(private l : Logger) {
  this.foo = "bar";
  this.l.log(this.foo);
}  

参见JSFiddle here

答案 1 :(得分:0)

您从未分配到this.l。所以固定代码:

class Logger {
  constructor() {}

  public log(msg : string) {
    console.log(msg);
  }
}

class Greeter {
  public foo: string;
  private l : Logger;
  constructor(l : Logger) {
    this.foo = "bar";
    this.l = l; // !!!!!This line is the fix!!!!!
    this.l.log(this.foo);
  }
}

let g = new Greeter(new Logger());
console.log(g.foo);