Search code examples
javascriptvariablesprototypeglobalextending

JavaScript prototype extending


I'm trying to extend an Abstract object.

var Abstract = function() { code = 'Abstract'; };
Abstract.prototype.getCode = function() { return code; };
Abstract.prototype.getC = function() { return c; };

var ItemA = function() { code = 'ItemA'; c = 'a'; };
ItemA.prototype = Object.create(Abstract.prototype);
ItemA.prototype.constructor = ItemA;

var ItemB = function() { code = 'ItemB'; };
ItemB.prototype = Object.create(Abstract.prototype);
ItemB.prototype.constructor = ItemB;

var b = new ItemB();
console.log(b.getCode());
var a = new ItemA();
console.log(b.getCode());
console.log(b.getC());

The result:

ItemB
ItemA
a

Is there any particular reason why I'm getting ItemA's scope in ItemB instance? How can I fix it?


Solution

  • It is because you are using global variables. Fix it by using this keyword:

    var Abstract = function() { this.code = 'Abstract'; };
    Abstract.prototype.getCode = function() { return this.code; };
    Abstract.prototype.getC = function() { return this.c; };
    
    var ItemA = function() { this.code = 'ItemA'; this.c = 'a'; };
    ItemA.prototype = Object.create(Abstract.prototype);
    ItemA.prototype.constructor = ItemA;
    
    var ItemB = function() { this.code = 'ItemB'; };
    ItemB.prototype = Object.create(Abstract.prototype);
    ItemB.prototype.constructor = ItemB;
    

    Although in this case ItemB.getC() will return undefined.