文章来源于网络收集而来,版权归原创者所有,如有侵权请及时联系!
十一、类
正确的做法
➖➖➖➖➖➖➖➖➖类➖➖➖➖➖➖➖➖➖ class Animal { constructor(name) { this.name = name; } sayHi() { return `My name is ${this.name}`; } } let a = new Animal('Jack'); console.log(a.sayHi()); // My name is Jack ➖➖➖➖➖➖➖➖➖继承➖➖➖➖➖➖➖➖➖ class Cat extends Animal { constructor(name) { super(name); // 调用父类的 constructor(name) console.log(this.name); } sayHi() { return 'Meow, ' + super.sayHi(); // 调用父类的 sayHi() } } let c = new Cat('Tom'); // Tom console.log(c.sayHi()); // Meow, My name is Tom ➖➖➖➖➖➖➖➖➖存储器➖➖➖➖➖➖➖➖➖ class Animal { constructor(name) { this.name = name; } get name() { return 'Jack'; } set name(value) { console.log('setter: ' + value); this.name = value; } } let a = new Animal('Kitty'); // setter: Kitty a.name = 'Tom'; // setter: Tom console.log(a.name); // Jack ➖➖➖➖➖➖➖➖➖静态方法➖➖➖➖➖➖➖➖➖ class Animal { static isAnimal(a) { return a instanceof Animal; } } let a = new Animal('Jack'); Animal.isAnimal(a); // true // 只能通过类名调用 a.isAnimal(a); // TypeError: a.isAnimal is not a function ❌ ➖➖➖➖➖➖➖➖➖抽象类➖➖➖➖➖➖➖➖➖ // 只能被继承,不能被实例化 abstract class Animal { eat(){ console.log('eat') } abstract sleep(): void } // 子类必须实现抽象类的抽象方法 class Dog extends Animal { constructor(name: string) { super() this.name = name } name: string; run() {} sleep() { console.log('dog sleep') } } let dog = new Dog('wang') dog.eat()
11.1 类与接口的关系
interface Human { name: string; eat(): void; } // 实现接口中声明的属性 class Person implements Human { constructor(name: string) { this.name = name } name: string; eat() {} }
// 接口可以像类一样实现继承 interface Man extends Human { run(): voild } interface Child { cry(): voild } interface Boy extends Man,Child {} // 添加被继承过来的属性 let body: Boy = { name: 'xx', run() {}, eat() {}, cry() {} }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论