user1561346
user1561346

Reputation: 502

Javascript subclassing

I expect this results in console: "2" and "11". But instead it gives me "2" and "2". Why publicFunc2 is not overriden? http://jsfiddle.net/17b5ytmq/1/. I guess I don't understand something about subclassing in Javascript.

function MyClass() {
    var self = this;
    this._protectedArr = [1];
    this.publicFunc = function() {
        this._protectedArr.forEach(function(element, index, array) {
            console.log(element + self.publicFunc2());
        });
    }
    this.publicFunc2 = function () {
        return 1;
    }
}

function MyClassChild() {
    this.publicFunc2 = function () {
        return 10;
    }
}

var myClass = new MyClass();
myClass.publicFunc();

MyClassChild.prototype = myClass;
var myClassChild = new MyClassChild()
myClassChild.publicFunc();

Upvotes: 0

Views: 252

Answers (1)

MrBar
MrBar

Reputation: 1106

You should inherit the prototype and not the instance like so:

MyClassChild.prototype = Object.create(MyClass.prototype);

also you should call the constructor function to truly inherit all of the class

function MyClassChild() {
    MyClass.call(this);

    this.publicFunc2 = function () {
        return 10;
    }
}

MyClassChild.prototype = Object.create(MyClass.prototype);

lastly, the this keyword is a dynamic reference to the current instance when used in methods.

when you assign this to a variable you create a static reference to the current instance that can be used like a reference to any other object.

Here is an explanatory example:

function MyClass() {
    var self1 = this;
    this.id = 'MyClass';

    this.publicFunc = function() {
        var self2 = this;
        asyncAction(function () {
            // self1 - MyClass
            // self2 - MyClass or MyClassChild - depends on the calling object
        });

        return self1.id + ' - ' + this.id;
    };

    this.publicFunc2 = function () {
        return 1;
    };
}

function MyClassChild() {
    MyClass.call(this);
    this.id = 'MyClassChild';

    this.publicFunc2 = function () {
        return 10;
    }
}
MyClassChild.prototype = Object.create(MyClass.prototype);

var myClass = new MyClass();
var myClassChild = new MyClassChild();

myClass.publicFunc(); // MyClass - MyClass
myClassChild.publicFunc(); // MyClass - MyClassChild

myClass.publicFunc2(); // 1
myClassChild.publicFunc2(); // 10

Upvotes: 1

Related Questions