2017-06-01 61 views
2

我有這麼多「這個」。在代碼:「this」的代碼重構。在功能

calculate(){ 
    this.value1 = this.fabrika.calc(this.value2); 
    this.value4 = this.other.other_calc(this.value10); 
    // etc 
} 

我怎麼可以這樣做:

calculate(){ 
    with this{ // error 
    value1 = fabrika.calc(value2); 
    value4 = other.other_calc(value10); 
    } 
} 

更漂亮的代碼

+2

沒有辦法做到這一點AFAIK,儘管你可以別名'this'爲't'減少長度。 (或者,使用閉包而不是類) – Gerrit0

+1

您可以使用解構語法'let {value2,value10} = this;'將多個值拉入一行中的範圍。儘管如此,任何作業當然不會影響「這個」。 – vu1p3n0x

+0

嗯,有一個真正的['with'](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with)關鍵字,但是有一些[強烈的反對使用它的論據](http://yuiblog.com/blog/2006/04/11/with-statement-considered-harmful/) – Saravana

回答

0

不知道這個例子幫助,但只需要聲明一個局部變量的東西更多legiable就像我在這個例子中爲const食品= this.foods;大聲笑沒有太多更好,但比這個食物在params中更好。

const foodMenu = { 
    foods: ['rice', 'beans', 'beef'], 
    getRandomFood: function() { 
     return() => { 
      const foods = this.foods; 
      const food_index = Math.floor(Math.random() * foods.length); 
      return foods[food_index]; 
     } 
    } 
} 

const getFood = foodMenu.getRandomFood(); 
console.log(getFood()); 

總而言之,我建議新的聲明變量,並將其放置在你的代碼在必要時並留下評論:d