javascript - 在打字稿中将数据从子类传递给父类
问题描述
我有 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 的新手。可能吗?
解决方案
使用继承有两种主要方法:
- 构造函数参数:
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();
- 子模板方法:
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();
推荐阅读
- sql - OVER 语句中的 COALESCE 函数不起作用
- python - 异步产生后,“继续”会发生什么?
- c - 我收到消息:无法在分配中将 'float' 转换为 'float*' 并且我有一些逻辑错误
- sqlite - 如何在 mac 上为 sqlite3 获取电子窗口绑定?
- android - 在 WhatsApp 等信使软件中发送和接收消息
- embedded-linux - 为什么我的内核配置选项在运行 bitbake -c savedefconfig virtual/kernel 后没有在结果 defconfig 中设置?
- ionic-framework - 单个组件的离子变化平台样式
- dart - 尽管调试显示列表中有 2 个元素,但 forEach 循环不会像列表为空一样执行
- lua - 带航向的 2 个航点之间的贝塞尔曲线
- git - 如何使 Github 预接收挂钩快速读入签入/提交的文件以进行验证?