gpt4 book ai didi

javascript - 如何设置从我自己的类到内置类的继承

转载 作者:行者123 更新时间:2023-12-03 01:53:59 25 4
gpt4 key购买 nike

如何设置从我自己的类到内置类的继承

我们有一个大的内置类 Image(例如我在 Canvas 中使用它来显示图像)。

img = new Image ()
img.onload = function () { .... }

我希望我的图像可以具有我自己的类 Counter 的方法和属性。

class Counter {
constructor {
this.orientation = orientation
}
}

如何从我的类 Counter 中设置类 Image 的继承(即不重写 Image 的构造函数)?也许这是一个微不足道的问题,但在我看到的所有类(class)中,创建了子类并从内置类获得了继承,现在我需要相反的情况。
也可能是错误的解决方法。在这种情况下,如果有人向我展示正确的方法,我将不胜感激,因为“我不知道我不知道什么”。

谢谢!

最佳答案

简单的方法 - 使用调用 Counter 的方法扩展 Image 原型(prototype):

Image.prototype.imageCount = function() {
let me = this;
let counter = new Counter();
return counter.count(me.numberOfImages);
}

// usage
let myImage = new Image();
myImage.numberOfImages = 42;
myImage.imageCount(); // will call counter

这样 Counter 方法就被封装在 Image 类中,并且是 Image 类原型(prototype)的一部分。

关于javascript - 如何设置从我自己的类到内置类的继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50313743/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com