简体   繁体   中英

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" eg 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?

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM