2

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?

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

But how can I extend "Product.Image" with "Product.BetterImage"? I want to use all methods from "Product.Image" in my "Product.BetterImage" but override one or two methods with it.
In the code above, whatever methods you put in betterImage will be there, if they are not they will fall back to the original Product.prototype. if you want to extend a prototype of product, its probably time to make a new class... did you read the docs? There are several ways to do this. hint: look at the docs, find the example at the bottom - its exactly what youre looking for

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.