Rami Loiferman
Rami Loiferman

Reputation: 912

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.

Upvotes: 7

Views: 2516

Answers (3)

Yusuf
Yusuf

Reputation: 2388

Use instance variables

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

// Class B dir is '/classes/b'
class B extends A{
  __dirname = __dirname;
}

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

Upvotes: 0

D. Ataro
D. Ataro

Reputation: 1831

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.

Upvotes: 1

Volem
Volem

Reputation: 636

You can do with overriding the method only. If you don't want this than you should not be using inheritance since this is based on inheritance definition.

Upvotes: -1

Related Questions