简体   繁体   English

如何扩展 Javascript 原型?

[英]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"但现在我需要扩展“Product.Image”,例如“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.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这与 javascript 继承和原型委托有关 - 请参阅这个好的 MDN 页面: 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然后要创建一个实例或实例化您使用的类,可以使用“new”关键字

var myProduct = new Product(data);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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