Search code examples
javascriptoverridingprototypeextend

How to extend Javascript Prototype?


I instantiate a function from my template with

new Product.Image({
        "title": document.querySelector('#image-title')
    });

But now I need to extend "Product.Image" e.g. with "Product.BetterImage"

new Product.BetterImage({
        "title": document.querySelector('#better-image-title')
    });

My original class starts like this:

Product.Image = function (options) {
  //do something
}
Product.Image.prototype = new Product.Data();

Now I tried to copy it to extend "Product.Image":

Product.BetterImage = function (options) {
  //do something
}
Product.BetterImage.prototype = new Product.Image();

But when I call my template to initiate it I got the following error:

Uncaught TypeError: Product.BetterImage is not a constructor

What am I missing here or what have done wrong? Can anyone explain me what's wrong here?


Solution

  • This has to do with javascript inheritance and prototype delegation - see this good MDN page: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

    This part of your code is not needed and causing the problem:

    Product.Image = function (options) {
      //do something
    }
    Product.Image.prototype = new Product.Data();
    

    The right way to do this is to create your 'Product' class and then add directly to its Prototype, like so:

    var Product = function(data) {
      this.data = data;
    }
    
    Product.prototype.image = function() {
       // return data here
    }
    
    Product.prototype.better = function(){
      // add stuff here
    }
    
    Product.prototype.betterImage = function(){
      // add more stuff here
    }
    

    then to create an instance or instantiate your class you use can use the 'new' keyword

    var myProduct = new Product(data);