Alberto Valero
Alberto Valero

Reputation: 440

JavaScript ES6 - Static method in parent class returns value set in child

I have this class structure:

class Component{
    constructor(name){
        this.__name = name;
    }

    static getName() { return this.__name; }
}   

class ComponentChild extends Component{
    constructor(){
        super("myName");
    }
}

When I call

console.log(ComponentChild.getName);

I would expect myName

Instead I get undefined.

Any help? Thanks!!

Upvotes: 0

Views: 902

Answers (2)

J. Pichardo
J. Pichardo

Reputation: 3115

In OOP static properties and functions belong to the class they are declared into, hence they do not have access to instance properties or functions, so you would need to make that function non-static.

getName() { return this.__name; }

Further explanation

You must take into consideration that JS is not a class-based but a prototype-based OOP language, before ES6 declaring a "static" function was done as a property of the constructor function:

function Component(name) {
     // ctor logic
}

Component.getName = function(){ 
     // fn logic 
}

So inside a "static" function your this is the constructor function.

Update

If you must use a static method you could write an accessor function like

class Component {
    static getName(instance) {
        return instance._name;
    }
}

And then use it as

console.log(Component.getName(instance));

Upvotes: 3

Máté Safranka
Máté Safranka

Reputation: 4116

You can't use this in a static function to refer to an instance. Static functions are static because you invoke them on the class itself, not an instance; thus, they have no access to instance members.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static

Upvotes: 1

Related Questions