class MySon extends Father { // constructor中的参数必须要满足父类。 // 除非父类有默认参数或者父类中的属性不是必须属性。 constructor(name: string, age: number) { // super调用父类中的构造函数 super(name,age) } // 子类中自己的实例方法 sonsay() { console.log('我是子类哈哈'); //调用父...
interfaceIPoint{// getter settersetY:number;getY:number;drawoPoint:() =>void;getDistances:(p:IPoint) =>number; }classPointimplementsIPoint{// private 修饰的变量、方法 要在接口中去掉(隐藏)constructor(private_x:number,private_y:number){this._x= _x;this._y= _y; }// settersetsetY(value...
*public: 允许我在类对内外被调用 *private:允许我在类内被使用 *protected: 允许在类内及继承的子类中使用 2、 class Person1 {constructor(public name: string){}//自动执行}//等同于class Person { public name: string; constructor(name: string){//自动执行this.name =name; } } 3、super 如果子类...
10.类的访问修饰符: private修饰私有属性,只能在类内部访问。public修饰公用属性(默认),外部也可访问: class Person { public name: string; private age: number; constructor(name:string,age:number){ this.name = name; this.age = age; } sayHi(msg:string):void { console.log(`hi,${msg},i am $...
private name: string; constructor(name: string) { this.name = name; // 可以在构造函数中访问和修改私有属性 } greet() { console.log(`Hello, my name is ${this.name}.`); // 可以在类的方法中访问私有属性 } } const person = new Person("Alice"); ...
private(私有的) 如果使用private来修饰属性, 那么表示这个属性是私有的 可以在类的内部使用 错误示例: image-20211128161154773 正确示例: 代码语言:typescript 复制 classPerson{name:string;age:number;privategender:string;constructor(name:string,age:number,gender:string){this.name=name;this.age=age;this.gender...
public(默认):公有,可以在任何地方被访问。protected:受保护,可以被其自身以及其子类访问。private:私有,只能被其定义所在的类访问。 示例: 代码语言:javascript 复制 classAnimal{name:string;privateage:number;constructor(name:string,age:number){this.name=name;this.age}eat():void{console.log(this.name+'ea...
公共public,私有private与受保护protected的修饰符 一般来说,在TypeScript里,成员都默认为public。 我们可以把上面的例子写成这样: classGreeter{publicgreeting:string;publicconstructor(message:string){this.greeting=message;}publicgreet(){return"Hello, "+this.greeting;}}letgreeter=newGreeter("world"); ...
private name: string; private surname: string; constructor(name: string, surname: string, age: number) { this.name = name; this.surname = surname; this.age = age; } getFullName() { return `${this.name} + ${this.surname}`;
TypeScript有两种方式来使类的字段私有化。一种是旧的private关键字,它是TypeScript特有的。然后是新的#somePrivateField语法,它参考自JavaScript。下面是一个例子,分别展示了它们: classMyClass{privatefield1:string;#field2: string;...}复制代码 我们推荐新的#somePrivateField语法,原因很简单:这两个特性大致等同...