使用函数对象和类分别定义 ES 和 TS 两个子类,实现继承案例

1、使用函数对象定义子类:

function Niyy() {
    
    
  this.name = "Niyy";
}

Niyy.prototype.sayHello = function () {
    
    
  console.log("Hello, I am " + this.name);
};

function ES() {
    
    
  Niyy.call(this); // 调用父类构造函数
  this.language = "JavaScript";
}

ES.prototype = Object.create(Niyy.prototype); // 设置原型链
ES.prototype.constructor = ES; // 修复构造函数指向

ES.prototype.sayLanguage = function () {
    
    
  console.log("I code in " + this.language);
};

function TS() {
    
    
  Niyy.call(this); // 调用父类构造函数
  this.language = "TypeScript";
}

TS.prototype = Object.create(Niyy.prototype); // 设置原型链
TS.prototype.constructor = TS; // 修复构造函数指向

TS.prototype.sayLanguage = function () {
    
    
  console.log("I code in " + this.language);
};

// 测试 ES 子类
const esInstance = new ES();
esInstance.sayHello(); // 输出 "Hello, I am Niyy"
esInstance.sayLanguage(); // 输出 "I code in JavaScript"

// 测试 TS 子类
const tsInstance = new TS();
tsInstance.sayHello(); // 输出 "Hello, I am Niyy"
tsInstance.sayLanguage(); // 输出 "I code in TypeScript"

2、使用类定义子类:

class Niyy {
    
    
  protected name: string;

  constructor() {
    
    
    this.name = "Niyy";
  }

  sayHello(): void {
    
    
    console.log(`Hello, I am ${
      
      this.name}`);
  }
}

class ES extends Niyy {
    
    
  private language: string;

  constructor() {
    
    
    super();
    this.language = "JavaScript";
  }

  sayLanguage(): void {
    
    
    console.log(`I code in ${
      
      this.language}`);
  }
}

class TS extends Niyy {
    
    
  private language: string;

  constructor() {
    
    
    super();
    this.language = "TypeScript";
  }

  sayLanguage(): void {
    
    
    console.log(`I code in ${
      
      this.language}`);
  }
}

// 测试 ES 子类
const esInstance = new ES();
esInstance.sayHello(); // 输出 "Hello, I am Niyy"
esInstance.sayLanguage(); // 输出 "I code in JavaScript"

// 测试 TS 子类
const tsInstance = new TS();
tsInstance.sayHello(); // 输出 "Hello, I am Niyy"
tsInstance.sayLanguage(); // 输出 "I code in TypeScript"

无论是使用函数对象还是类来定义子类,都可以通过调用父类的构造函数(Niyy.call(this)super())来继承父类的属性,并通过设置原型链和修复构造函数指向来继承父类的方法。子类可以添加自己的属性和方法,以及重写父类的方法。在示例中,ES 子类和 TS 子类都继承了 Niyy 父类,并添加了各自的语言属性和方法。

猜你喜欢

转载自blog.csdn.net/m0_37577465/article/details/131781654