简体   繁体   English

打字稿:您可以在类的私有属性中使用构造函数属性吗?

[英]Typescript: can you use constructor properties within a class's private properties?

Is it bad practice to use a constructor properties of a class within a variable?在变量中使用类的构造函数属性是不好的做法吗? I tried this and was surprised const name = new Name(time, course);我试过了,很惊讶const name = new Name(time, course); worked, although I guess it makes sense since an instance of Eng needs those constructor properties to be made, then they'd be available to use elsewhere.工作,虽然我认为这是有道理的,因为Eng的实例需要制作这些构造函数属性,然后它们可以在其他地方使用。

import { Name } from './Name'

class Eng {
   private _name = new Name(time, course);

   private constructor(time: String, course: String) {} 

   method1(){
      let results = name.convertTrials();

      return results;
   }
}

Your code example actually has type errors:您的代码示例实际上有类型错误:

class Eng {
   private _name = new Name(time, course);
   // Cannot find name 'time'.(2304)
   // Cannot find name 'course'.(2304)

   private constructor(time: string, course: string) {} 
}

time and course are not in scope as far as typescript is concerned.就打字稿而言, timecourse不在范围内。 If you want to use constructor parameters, they must be in constructor body.如果要使用构造函数参数,它们必须在构造函数体中。


What may be confusing you is that, when compiled, the code runs fine.可能让您感到困惑的是,在编译时,代码运行良好。 That is because non-static class properties are moved into the constructor for you, since that is where they would need to be in plain JS.那是因为非静态类属性被移动到你的构造函数中,因为那是它们需要在纯 JS 中的位置。

So your compiled class looks like:所以你编译的类看起来像:

// js
class Eng {
    constructor(time, course) {
        this._name = new Name(time, course);
    }
}

Which should work without a problem.哪个应该没有问题。

But it is a problem for Typescript, which believes that the constructor arguments are not in scope outside of the constructor.但这对于 Typescript 来说个问题,它认为构造函数参数不在构造函数之外的范围内。


If you don't need the arguments:如果您不需要参数:

class Foo {
    constructor() {}
}

class UseFoo {
   private foo = new Foo()
   private constructor() {} 
}

Then there isn't anything wrong with your approach.那么你的方法没有任何问题。

See Playground 见游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM