在角度2中,我注意到有几种方法可以使用=
和:
使用public
声明变量。
示例:
public heroes = HEROES;
title = "Tour of Heroes";
selectedHero: Hero;
有什么区别?它只是关于初始化和未初始化的吗?
答案 0 :(得分:5)
因为javascript没有type checking
意味着您可以执行someVar="hello"
,之后您可以指定其他类型的值,例如。像someVar=true
一样的布尔值,这在javascript中很好。 类型脚本为javascript的其他功能提供了类型检查功能。这与初始化无关。
=
设置变量的值:
设置变量的类型在你的例子中:
public heroes = HEROES; // assigns value of HEROES to heroes, heroes now has an inferred type same as the type of HEROES
title = "Tour of Heroes"; // normal assignment with inferred type of 'string'
selectedHero: Hero; // just declares selectedHero with the type 'Hero'
您可以同时设置值和类型:
title:string = "some text"; // this means, title is of type string and has the value "some text"
稍后如果你这样做,title=true
编译器会给你一个警告,因为你试图将boolean值赋给一个类型为string的变量。
<强>附加强> 您还可以设置多种类型而不只是一种:
title:string|boolean=true; // title is of type either string or boolean
title:"text1"|"text2"|"text3"; // (v1.8 and after) title is of type string and can have only one of the values: "text1","text2" or "text3". in other words enum type
title:any; // title is of any type.
关于功能声明:
someFunction(name:string):boolean{
// the parameter 'name' is expected to be of type string in the body of this function
return true; // the return type of the function is expected to be boolean
}
Lambda Expression:
someFunction = (name:string):boolean => {
// the variable name is expected to be of type string in the body of this function
return true;
}
答案 1 :(得分:3)
:定义变量的类型并且不初始化
=初始化变量并隐含地定义其类型
public将变量定义为public,即可从类外部访问(与私有相对)