0

I have 2 classes(Model). I want to use some properties in parent class, which are defined in child. Is it possible?

Parent Class:

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

Child Class:

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

In my controller I am calling as like this.

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

I am new in OOP. Is it possible?

Sarower Jahan
  • 1,445
  • 1
  • 13
  • 20
  • I don't think thats how OOP and Inheritance work. Child classes inherit from the parent class. I also don't think you're doing things right here. Why aren't you declaring table in the parent class? – Wali Waqar Jul 03 '21 at 11:08
  • I want to use parent class for all tables. My concept is=> child class represents the table info and parent class represents the dynamic queries. – Sarower Jahan Jul 03 '21 at 11:37
  • In that case you still declare the property in the parent class, but reassign it the values in the child classes. Have a look at this answer: https://stackoverflow.com/a/55479942/10198411 – Wali Waqar Jul 03 '21 at 13:02
  • Does this answer your question? [Access JavaScript class property in parent class](https://stackoverflow.com/questions/55479511/access-javascript-class-property-in-parent-class) – Wali Waqar Jul 03 '21 at 13:03
  • Forgot this question? – plalx Jul 09 '21 at 05:23

1 Answers1

1

There's 2 main ways to do it using inheritance:

  1. Constructor argument:

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. Template method in child:

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();
plalx
  • 42,889
  • 6
  • 74
  • 90