Home > Software design >  How to call a child static function from parent in javascript?
How to call a child static function from parent in javascript?

Time:12-09

Maybe what i'm looking for is impossible but it would be very convenient for my needs

class Music extends Database {
    static ref(id){return `musics/${id}`}
}

class Book extends Database {
    static ref(id){return `books/${id}`}
}

class Database {
    static fetch(id){
        const data = request(Database.children.ref(id)) // <===== HERE of course the 'children' function doesn't exists 
        return new this(data)
    }
}

Music.fetch(‘1234’) 

Book.fetch(‘9876’)

How to call a the static ref function from the static fetch function in the parent ?

This will avoid to copy the 'fetch' function in all children class

If this is an anti-pattern solution, what can I do ?

CodePudding user response:

The relationship is the opposite: children can refer to their parent.

You can have a generic static method in the parent (Database) that the children just call with appropriate data:

class Database {
    static fetch(data, type){
        console.log(`requesting data: ${data} for type: ${type}`);
    }
}

class Music extends Database {
    static fetch(id){ return super.fetch(`musics/${id}`, "Music"); }
}

class Book extends Database {
    static fetch(id){ return super.fetch(`musics/${id}`, "Book"); }
}


Music.fetch('1234')
Book.fetch('9876')
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Alternatively, the parent can still access data from this, so you can use it to access the child:

class Database {
    static fetch(data){
        console.log(`requesting data: ${data} for type: ${this.myType}`);
    }
}

class Music extends Database {
    static myType = "Music";
    static fetch(id){ return super.fetch(`musics/${id}`); }
}

class Book extends Database {
    static myType = "Book";
    static fetch(id){ return super.fetch(`musics/${id}`); }
}


Music.fetch('1234')
Book.fetch('9876')
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

Your code could be done with using this

Show code snippet

class Database {
    static fetch(id){
        console.log(`requesting data: ${this.ref(id)}`);
    }
}

class Music extends Database {
    static ref(id){return `musics/${id}`}
}

class Book extends Database {
    static ref(id){return `books/${id}`}
}


Music.fetch('1234')
Book.fetch('9876')
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

However, I would advise against it. It puts all the responsibility of the inheriting classes to work the same, instead of putting all the logic in the parent and the inheriting classes do the minimal work necessary.

  • Related