Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, how can you access a property of a superclass' instance?

In JavaScript, how can I access a property of a superclass' instance? As an example, I'd like the "prop" of the superclass' instance set to "true", but this code creates and sets the "prop" of the subclass' instance to "true", leaving the superclass' instance's "prop" as false:

var SuperClass = function() {
    this.prop = true;
}

SuperClass.prototype.doStuff = function() { 
    if (this.prop) {
        console.log('SuperClass does A.');
    }
    else {
        console.log('SuperClass does B.');
    }
}

SuperClass.prototype.load = function() {
    this.prop = false;
}

SuperClass.prototype.setProp = function(val) {
    this.prop = val;
}

function SubClass() {
    SuperClass.call(this);
}

SubClass.prototype = Object.create(SuperClass.prototype);
SubClass.prototype.constructor = SubClass;

SubClass.prototype.doStuff = function() {
    SuperClass.prototype.doStuff();

    if (this.prop) {
        console.log('SubClass does A.');
    }
    else {
        console.log('SubClass does B.');
    }
}

SubClass.prototype.load = function() {
    SuperClass.prototype.load();
}

var anObject = new SubClass();
anObject.load();
anObject.setProp(true);
anObject.doStuff();

Currently, the output is "SuperClass does B. SubClass does A.", which is not the desired result. How do I properly set the value of "prop" so that they both do "A"? I'm not trying to create a new property in the subclass' instance, I want to access the existing property in the superclass' instance.

Thanks!

Additionally, can you access a superclass' instance's properties from a subclass' constructor? Or does the subclass need to be instantiated first?

like image 505
PolkaPunk Avatar asked Oct 29 '25 16:10

PolkaPunk


1 Answers

SubClass.prototype.doStuff = function() {
    SuperClass.prototype.doStuff();

You aren't giving the super class any context, so the function isn't acting on the current object (i.e. this will be wrong).

Instead try:

SubClass.prototype.doStuff = function() {
    SuperClass.prototype.doStuff.call(this);

This gives me the desired output:

SuperClass does A.
SubClass does A.
like image 147
James McLaughlin Avatar answered Nov 01 '25 07:11

James McLaughlin