编译打字稿。函数原型丢失了对 "this" 的引用

Compiled typescript. Function prototype lost reference to "this"

我正在使用 Typescript 使用 Redux 和 Maquettejs 编写 todo-app 示例。我只是编译 typescript,然后我使用 browserify 来捆绑所有的 .js 文件(这个文件包含应用程序 .ts 文件,以及库 [redux, maquettejs]),编译时没有错误,一切正常。

当我尝试在浏览器上查看结果时出现此错误。

至少对我来说它没有意义,因为它是明确定义的。我不是判断编译代码的专家,但以防万一我创建了一个模拟实现 http://jsbin.com/tenohitumi/edit?js,console,output 并且它按预期工作。我真的不明白发生了什么。

以防万一这是用打字稿写的 class "App"。

import { h, VNodeProperties, VNode } from 'maquette';
import { Store } from 'redux';
import { TodoList } from './Todolist';

export class App {

    constructor(private store: Store<any>) {
    }

    render(): VNode {
        this.store;
        return h('div.main-component', [
            new TodoList(this.store).render()
        ]);
    }
}

// This is how I create the instance (it's in a different file)

import { createStore } from 'redux';
import { createProjector } from 'maquette';

import * as I from './interfaces/app';
import { MainReducer } from './reducers';
import { App } from './components/App';

let store = createStore(MainReducer);

let projector = createProjector();


document.addEventListener('DOMContentLoaded', function () {
  let app = new App(store);
  projector.append(document.body, app.render);
});

我想知道匿名函数之外的东西(在包本身中)是否会影响 "this" 的值,或者阻止它被设置?

正如@squint 在评论中回答的那样,当您将 render 方法传递给 projector.append 时,它会从其 App 实例中孤立出来。考虑更换原来的行

projector.append(document.body, app.render);

projector.append(document.body, () => app.render());

或者,您可以使用箭头函数来定义 render,它不会保留其对 this.

的原始引用
export class App {
    constructor(private store: Store<any>) {
    }

    render = (): VNode => {
        return h('div.main-component', [
            new TodoList(this.store).render()
        ]);
    }
}