【问题标题】:extending property form outside of constructor在构造函数之外扩展属性形式
【发布时间】:2012-11-29 05:16:00
【问题描述】:

假设我有这样的事情:

interface Scope extends ng.Scope {
   getMeSome(id:string):number[];
}
export class AwesomeController {
    constructor (public $scope:Scope) {
       $scope.getMeSome = id => this.getMeSome(id);
    }
    getMeSome(id:string){
      console.log('Alright... alright... here it is'); 
    }
}

现在你可以看到我在 3 个不同的地方有相同的方法签名。当然,我可以把它剪掉一点,然后在构造函数中执行它:

constructor (public $scope:Scope) {
   $scope.getMeSome = id => {
      console.log('Alright... alright... here it is'); 
   };
}

但这会让构造函数的身体像打了类固醇一样(如果你有几十种不同的方法)。 所以我想知道为什么我不能这样做:

export class AwesomeController {
   constructor (public $scope:Scope) { }

   $scope.getMeSome(id:string) { // Can't extend $scope here, although I can do that in the constructor
      console.log('Alright... alright... here it is'); 
   }
}

为什么这不起作用?有什么让它更性感的建议吗?

【问题讨论】:

    标签: typescript


    【解决方案1】:

    据我所知,在类中(与在模块中不同),您是在定义类,而不是运行类,所以你不能这样做类主体中的任何分配(与方法主体相反)。所以这个语法不起作用:

    export class AwesomeController {
        constructor (public $scope:Scope) {}
        $scope.getMeSome = id => {
          console.log('Alright... alright... here it is'); 
        }
    }
    

    您还只是定义了 this 类的方法,而不是其他类的方法,因此您上面的语法也不起作用,因为它与不同类的方法混为一谈在您只需要定义自己的地方:

    export class AwesomeController {
        constructor (public $scope:Scope) {}
        $scope.getMeSome(id:string) => {
          console.log('Alright... alright... here it is'); 
        }
    }
    

    我认为你只需要按照你提出的前两种方法之一来做——这两种方法对我来说都很好。

    【讨论】:

    • 好吧,我们是开发人员,看到漂亮的代码很自然会被唤醒。我想也许可以让它变得更好。但是,您的回答完全有道理。谢谢。
    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 2016-04-25
    • 2016-07-26
    • 2012-06-11
    • 2012-01-09
    • 1970-01-01
    • 2016-06-19
    • 1970-01-01
    相关资源
    最近更新 更多