原型继承是一个强大的 JavaScript 范例,但管理大型应用程序可能具有挑战性。考虑一个具有众多函数的轮播类:
Carousel.prototype.next = function () {...} Carousel.prototype.prev = function () {..} Carousel.prototype.bindControls = function () {..}
为了更好的代码组织而进行的重构可能涉及将函数分组为子对象:
Carousel.prototype.controls = { next: function () { ... } , prev: function() { ... }, bindControls: function () { .. } }
但是,此更改引入了一个问题:这些函数中的“this”关键字不再引用轮播实例。
维护“this”上下文至关重要,尤其是在类继承父类的情况下。继承类中的重写函数必须保留正确的“this”行为。
一种方法是将 Controls 定义为单独的类并存储引用到轮播实例:
var Controls = function (controllable_object) { this.ref = controllable_object; }; Controls.prototype.next = function () { this.ref.foo(); } // ..
虽然此解决方案解决了“this”问题,但它阻止了 Controls 实现的重写。
更灵活的方法涉及依赖注入:
var Controls = function (controllable_object) { this.ref = controllable_object; }; Controls.prototype.next = function () { this.ref.foo(); } // .. var Carousel = function () { this.controllers = []; }; Carousel.prototype.addController = function (controller) { this.controllers.push(controller); }; // ..
在这种情况下,轮播类可以添加多个控制器,容纳多组功能并允许轻松覆盖。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3