constructor 的private和public 区别和用途
公有,私有于受保护的修饰符
默认为 public
在上面的例子里,我们可以自由访问程序里定义的成员,在TypeScript里,成员默认为public,你也可以明确的将一个成员标记成public。
class Animal {
public name: string;
public constructor(theName: string){
this.name = theName;
}
public move(distanceInMeters: number){
console.log(`${this.name} moved ${distanceInMeters}m.`);
}
}
还要注意的是,在构造函数的参数上使用public等同于创建了同名的成员变量
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);
理解private
当成员被标记成private时,它就不能在声明它的类的外部访问:
class Person{
protected name: string;
constructor(name: string){
this.name = name;
}
}
class Employee extends Person{
private department: string;
constructor(name: string, department: string){
super(name)
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employe("Howard", "Sales");
console.log(howard.getElevatorPitch());
console.log(howard.name); // 错误
注意:我们不能在Person类外使用name,但是我们仍然可以通过Employee类的示例方法访问,因为Employee是由Person派生而来
构造函数也可以被标记成 protected。 这意味着这个类不能在包含它的类外被实例化,但是能被继承。比如,
class Person {
protected name: string;
protected constructor(theName: string) { this.name = theName; }
}
// Employee 能够继承 Person
class Employee extends Person {
private department: string;
constructor(name: string, department: string) {
super(name);
this.department = department;
}
public getElevatorPitch() {
return `Hello, my name is ${this.name} and I work in ${this.department}.`;
}
}
let howard = new Employee("Howard", "Sales");
let john = new Person("John"); // 错误: 'Person' 的构造函数是被保护的.
readonly修饰符
你可以使用 readonly关键字将属性设置为只读的。 只读属性必须在声明时或构造函数里被初始化。
class Octopus {
readonly name: string;
readonly numberOfLegs: number = 8;
constructor (theName: string) {
this.name = theName;
}
}
let dad = new Octopus("Man with the 8 strong legs");
dad.name = "Man with the 3-piece suit"; // 错误! name 是只读的.
完整例子
class TestClass {
constructor(name: string, private address: string, public city){
testMethod(){
console.log(this.name)// Compiler error: property 'name' does not exist on type 'TestClass'.
console.log(this.address);
console.log(this.city);
}
}
}
const testClass = new TestClass('Johnson', '8 gaoke road', 'NanNing');
testClass.testMethod();
console.log(testClass.name); // Compiler error: property 'name' does not exist on type 'TestClass'.
console.log(testClass.address); // Compiler error: 'address' is private and only accessible within class 'TestClass'.
console.log(testClass.city) // NanNing