打字稿"这"实例在类中未定义

时间:2018-03-16 11:10:34

标签: angular typescript

我在网上发现了这个,现在试图把它放在TS中。

运行以下投掷Uncaught TypeError: Cannot set property 'toggle' of null

@Injectable()
export class HomeUtils {
    private canvas: HTMLCanvasElement;
    private context;
    private toggle = true;

    constructor() { }

    public startNoise(canvas: HTMLCanvasElement) {
        this.canvas = canvas;
        this.context = canvas.getContext('2d');
        this.resize();
        this.loop();
    }

    private resize() {
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
    }

    private loop() {
        this.toggle = false;
        if (this.toggle) {
            requestAnimationFrame(this.loop);
            return;
        }
        this.noise();
        requestAnimationFrame(this.loop);
    }

    private noise() {
        const w = this.context.canvas.width;
        const h = this.context.canvas.height;
        const idata = this.context.createImageData(w, h);
        const buffer32 = new Uint32Array(idata.data.buffer);
        const len = buffer32.length;
        let i = 0;

        for (; i < len;) {
            buffer32[i++] = ((255 * Math.random()) | 0) << 24;
        }

        this.context.putImageData(idata, 0, 0);
    }

}

我输了。

2 个答案:

答案 0 :(得分:6)

方法不捕获this,并且依赖于调用者使用正确的this来调用它们。例如:

this.loop() // ok
let fn = this.loop;
fn(); // Incorect this
fn.apply(undefined) // Undefined this

由于您将loop传递给另一个函数requestAnimationFrame,因此您需要确保从声明上下文中捕获this,而不是由requestAnimationFrame决定:

您可以将箭头功能传递给requestAnimationFrame

private loop() {
    this.toggle = false;
    if (this.toggle) {
        requestAnimationFrame(() => this.loop());
        return;
    }
    this.noise();
    requestAnimationFrame(() => this.loop());
} 

或者你可以使循环成为箭头函数而不是方法:

private loop = () => {
    this.toggle = false;
    if (this.toggle) {
        requestAnimationFrame(this.loop);
        return;
    }
    this.noise();
    requestAnimationFrame(this.loop);
}

第二种方法的优点是不会在每次调用requestAnimationFrame时创建新的函数实例,因为这将被调用很多,您可能希望使用第二个版本来最小化内存分配。

答案 1 :(得分:3)

拨打requestAnimationFrame。您正在传递未绑定到上下文的函数,因此,在对loop的调用中,没有this

将通话更改为:

requestAnimationFrame(() => this.loop());

与正常函数相反,箭头函数绑定到this