2016-12-04 49 views
0

我目前偶然發現綁定的問題,我相信它會降低我的性能。在每次遞歸調用綁定看起來都很糟糕。優雅和高性能替代綁定()

林目前正在尋找處理這種情況的優雅和高性能的方式:

什麼是在這種情況下,理想是什麼?

class AlotMonster { 
    constructor() { 
     this.names = ['a lot', 'alot']; 
     this.method(); 
     } 

    method() { 
     let choice = Math.round(Math.random()); 
     let currentName = this.names[choice]; 

     console.log(currentName); 

     requestAnimationFrame(this.method.bind(this)); 
     } 
} 

new AlotMonster(); 
+5

在構造'this.boundMethod =這只是把它一次。 method.bind(this);'並在隨後的調用中使用'this.boundMethod'。 – georg

+0

@georg認真嗎?沒有想過它 – Asperger

+0

@georg這可能是一個問題performancewise?綁定我的意思是 – Asperger

回答

1

你可以改爲使用箭頭函數,它具有詞法this綁定。它看起來並不像你利用你的方法的原型性質,並希望它成爲通緝令特定的實例反正:

class AlotMonster { 
    constructor() { 
     this.names = ['a lot', 'alot']; 

     this.method =() => { 
      let choice = Math.round(Math.random()); 
      let currentName = this.names[choice]; 

      console.log(currentName); 

      requestAnimationFrame(this.method); 
     }; 

     this.method(); 
    } 
} 

new AlotMonster(); 
+0

這是更好的表現嗎? – Asperger