首页 > 解决方案 > 在打字稿中将数据从子类传递给父类

问题描述

我有 2 个课程(模型)。我想在父类中使用一些属性,这些属性是在子类中定义的。可能吗?

家长班:

class Model{
    constructor() {
        //I need the table name here. which is defined in child. 
    }  
    public static getAll(){
        return 'From Root Model';
    }
}
export default Model;

儿童班:

import Model from "../providers/Model";
class Product extends Model{
    public table="products";
}
export default Product;

在我的控制器中,我这样调用。

import Product from "../model/Product";
...
Product.getAll();

我是 OOP 的新手。可能吗?

标签: javascriptnode.jstypescriptexpressoop

解决方案


使用继承有两种主要方法:

  1. 构造函数参数:

class Model {
    constructor(table) {
        this.table = table;
    }
    
    getAll() {
        console.log(`Get all from ${this.table}.`);
    }
}

class Product extends Model {
    constructor() {
      super('product');
    }
}

new Product().getAll();

  1. 子模板方法:

class Model {
   
    getAll() {
        console.log(`Get all from ${this.tableName()}.`);
    }
    
    // This would be an abstract method
    tableName() {
      throw new Error('Not implemented');
    }
}

class Product extends Model {
    
    tableName() {
        return 'product';
    }
}

new Product().getAll();


推荐阅读