class Student {
fullName: string;
constructor(public firstName, public middleInitial, public lastName) {
this.fullName = firstName + " " + middleInitial + " " + lastName;
}
}
interface Person {
firstName: string;
lastName: string;
}
function greeter(person : Person) {
return "Hello, " + person.firstName + " " + person.lastName;
}
let user = new Student("Jane", "M.", "User");
document.body.innerHTML = greeter(user);
还要注意的是,在构造函数的参数上使用public等同于创建了同名的成员变量。 意思是说
class Student {
fullName: string;
constructor(public firstName, public middleInitial, public lastName) {
this.fullName = firstName + " " + middleInitial + " " + lastName;
}
}
等同于
class Student {
fullName: string;
firstName:string;
middleInitial:string;
lastName:string;
constructor( firstName, middleInitial, lastName) {
this.fullName = firstName + " " + middleInitial + " " + lastName;
}
}