注意点
- 在
TS 中如果定义了实例属性, 那么就必须在构造函数中使用, 否则就会报错
错误示例:
class Person {
name: string;
age: number;
}
正确示例:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
let p = new Person('BNTang', 18);
console.log(p);
利用 可选参数 解决不想使用的属性:
class Person {
name: string;
// 可选属性
age?: number;
constructor(name: string, age?: number) {
this.name = name;
this.age = age;
}
}
let p = new Person('BNTang');
console.log(p);
在来看看直接定义一个构造函数的情况下,通过对于的类创建出来的对象是什么样子的:
class Person {
constructor(name: string, age: number) {
}
}
let p = new Person('BNTang', 18);
console.log(p);
参数属性
class Person {
constructor(public name: string, public age: number) {
}
}
let p = new Person('BNTang', 18);
console.log(p);
如上代码类同如下代码:
class Person {
name: string;
age: number;
constructor(name: string, age: number) {
this.name = name;
this.age = age;
}
}
|
请发表评论