Typescript"this"实例在课堂上未定义

Rel*_*elm 4 typescript angular

我发现这个和在线,现在试图把它放在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);
    }

}
Run Code Online (Sandbox Code Playgroud)

我迷路了.

Osc*_*Paz 6

这是对 的调用requestAnimationFrame。您正在传递一个未绑定到上下文的函数,因此,在该调用loop中没有this.

将调用更改为:

requestAnimationFrame(() => this.loop());
Run Code Online (Sandbox Code Playgroud)

与普通函数相反,箭头函数绑定到this


Tit*_*mir 6

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

this.loop() // ok
let fn = this.loop;
fn(); // Incorect this
fn.apply(undefined) // Undefined this
Run Code Online (Sandbox Code Playgroud)

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

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

private loop() {
    this.toggle = false;
    if (this.toggle) {
        requestAnimationFrame(() => this.loop());
        return;
    }
    this.noise();
    requestAnimationFrame(() => this.loop());
} 
Run Code Online (Sandbox Code Playgroud)

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

private loop = () => {
    this.toggle = false;
    if (this.toggle) {
        requestAnimationFrame(this.loop);
        return;
    }
    this.noise();
    requestAnimationFrame(this.loop);
}
Run Code Online (Sandbox Code Playgroud)

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

  • “方法不能捕捉到这一点”——多么伟大的语言 (5认同)
  • 好的,我明白了,这会给我带来麻烦,感谢正确的解释。 (2认同)