繁体   English   中英

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

[英]Compiled typescript. Function prototype lost reference to “this”

我使用Typescript处理Redux和Maquettejs的todo-app示例。 我只是编译打字稿,然后使用browserify捆绑所有.js文件(此文件包含应用程序.ts文件和库[redux,maquettejs]),编译时没有任何错误,一切正常。

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

在此处输入图片说明

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

以防万一,这是用打字稿编写的“ 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方法正从它的孤立的App实例,当你把它传递给projector.append 考虑替换原始行

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()
        ]);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM