代码重构"这个。"在功能上

时间:2017-06-01 04:06:14

标签: typescript

我有这么多"这个。"在代码中:

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);
  }
}

这是更漂亮的代码

1 个答案:

答案 0 :(得分:0)

不确定这个例子是否有帮助,但只是将局部变量声明为更合法的东西,就像我在本例中对const foods = this.foods所做的那样;大声笑不是比这更好,但比这更好。食物在参数中。

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