Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript how to get subclass '__dirname' from super class

I want to create a method in a parent class that will return the location of each subclass that extends it.

// Class A dir is '/classes/a/
class A{      
    getPath(){
        console.log(__dirname);
        return (__dirname);
    }
}

// Class B dir is '/classes/b'
class B extends A{ 

}

new A().getPath(); // Prints '/classes/a'
new B().getPath(); // Prints '/classes/a' (I want here '/classes/b');

I understand why class B prints the location of A, but I'm looking for an option of making a method on the parent class that will print the subclass's location. I don't want to override the method in every subclass because it missing the point

I tried process.pwd() as well.

like image 738
Rami Loiferman Avatar asked Jan 18 '17 06:01

Rami Loiferman


1 Answers

If you are into slightly more hacky approaches, which might be required to be updated in the future, you can retrieve the path of the subclass quite easily. You have your class that extends another class (or a class that does not extend anything for that matter):

module.exports = class B extends A
{ 
    // TODO: implement
}

In order to retrieve the path of that class, we can do the following:

/* For this method we need to have the constructor function itself. Let us pretend that this
 * was required by a user using our framework and we have no way of knowing what it actually 
 * is from the framework itself.
 */
let B = require('path-to-b')
let path = require('path')
let dirOfB

for (let [, val] of require('module')._cache)
    if (val.exports === B)
        dirOfB = path.dirname(val.filename)

console.log(dirOfB)

// Expected output: path-to-b

This approach, even though slightly hacky, works well if we have the constructor function, but are unsure of the directory it actually lies within.

like image 102
D. Ataro Avatar answered Oct 10 '22 19:10

D. Ataro