[英]How to use TypeScript constructor to declare variables
I'm trying to use TypeScript
constructor in an Angular2 project, and I got confused regarding how to use class
constructor to initialize the variables: 我试图在Angular2项目中使用
TypeScript
构造函数,但对于如何使用class
构造函数初始化变量感到困惑:
function Auto () {
this.move = function () {
console.log('move');
}
this.stop = function () {
console.log('stop');
}
}
Now I will use it in the class: 现在,我将在课堂上使用它:
class Car {
constructor(private _auto: Auto) {
}
onMove() {
this._auto.move();
}
}
When I try to compile, I get this error Cannot find name Auto
, so could anyone help me understanding what's going on? 当我尝试编译时,出现此错误
Cannot find name Auto
,那么有人可以帮助我了解发生了什么吗?
And, why private _auto: Auto
make _auto
a new instance of Auto
class? 而且,为什么要
private _auto: Auto
使_auto
成为Auto
类的新实例?
Update: I know that I can use class
to solve the problem, but I want to understand why javascript
functions throw this error. 更新:我知道我可以使用
class
来解决问题,但是我想了解为什么javascript
函数会引发此错误。
The problem is happening because creating a function does not create a type for the compiler to use, so Auto
does not exist as a type. 发生问题是因为创建函数不会为编译器创建要使用的类型,因此
Auto
不存在为类型。 Right now it's only known as the name of a function. 现在,它仅被称为函数的名称。
The easiest way to solve this is to use a class for Auto
instead: 解决此问题的最简单方法是为
Auto
使用一个类:
class Auto {
move() {
console.log('move');
}
stop() {
console.log('stop');
}
}
Then you can do: 然后,您可以执行以下操作:
let auto = new Auto();
let car = new Car(auto);
Alternatively, you could manually describe the type of the function. 或者,您可以手动描述函数的类型。 Here's one example, but don't do this because you should just convert it to a class:
这是一个示例,但是不要这样做,因为您应该将其转换为类:
interface AutoConstructor {
new(): Auto;
}
interface Auto {
move(): void;
stop(): void;
}
let Auto: AutoConstructor = function() {
let self = this as Auto;
self.move = function () {
console.log('move');
}
self.stop = function () {
console.log('stop');
}
} as any;
let auto = new Auto();
let car = new Car(auto); // ok
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.