Search code examples
javascriptinheritanceprototype-oriented

I am doing something wrong with this prototype in JavaScript, any ideas?


The following code doesn't produce a prototype like I thought it might. Can anyone see what I am doing wrong?

var A = function () {
    return {
        workingTest: function () {return "OK";}
    };
};

A.prototype.notWorkingTest = function () {return "Not so much";};

var a = new A();

a.workingTest(); // "OK"
a.notWorkingTest(); // TypeError: "undefined_method"

Any ideas? I thought that this was the right way to extend JS classes, but I am missing something.


Solution

  • Change A to

    var A = function () {
      this.workingTest = function () {return "OK";};
    };
    

    The problem is that your original A function was creating and returning a direct instance of Object instead of using the instance of A that was created by the new operator and bound to this.

    To understand this, try running

    var B = function () { return { x: 42 }; }
    var C = function () { this.x = 42; }
    var b = new B;
    var c = new C;
    alert("b.constructor === B : " + (b.constructor === B));  // false
    alert("b.constructor === Object : " + (b.constructor === Object));  // true
    alert("c.constructor === C : " + (c.constructor === C));  // true
    

    So because B returns a new object, the value it returns is no longer an instanceof B and does not use B's prototype.