ES6中函數調用自身需要注意的問題


在傳統的遞歸調用中,可以采用如下方式

function sum(n) {
    return sum(n - 1) + n;
}

但如今es6盛行,為了保持代碼一致性,可以采用兩種解決方式。

第一種,將this重新綁定到回調

this.rendering= this.rendering.bind(this);
rendering() {
    requestAnimationFrame(this.rendering);
    this.cube.rotation.x += 0.1;
    this.cube.rotation.y += 0.1;
    this.renderer.render(this.scene, this.camera);
}

第二種方式使用箭頭函數自動綁定到this

rendering() {
    requestAnimationFrame(()=>this.rendering);
    this.cube.rotation.x += 0.1;
    this.cube.rotation.y += 0.1;
    this.renderer.render(this.scene, this.camera);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM