簡體   English   中英

Typescript“this”實例在課堂上未定義

[英]Typescript “this” instance is undefined in class

我發現這個和在線,現在試圖把它放在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);
    }

}

我迷路了。

方法不抓住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創建新的函數實例,因為這將被調用很多,您可能希望使用第二個版本來最小化內存分配。

這是對requestAnimationFrame的調用。 您正在傳遞一個未綁定到上下文的函數,因此,在該loop調用中沒有this

將通話更改為:

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

與正常功能相反,箭頭功能與this

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM