Home >Web Front-end >JS Tutorial >How Can I Organize JavaScript Prototypes While Preserving \'this\' References and Inheritance?
Organizing JavaScript Prototypes with Preserved References and Inheritance
To organize code effectively when using JavaScript prototypes and inheritance, a common issue arises with the loss of the "this" value in customized prototypes. In this problem, the intent is to organize code by compartmentalizing functionalities into nested objects while maintaining reference and inheritance.
Proposed Solution:
One approach to resolving this issue is to create a dedicated class for the functionality in question rather than nesting it directly within the prototype itself.
var Controls = function (controllable_object) { this.ref = controllable_object; }; Controls.prototype.next = function () { this.ref.foo(); } // .. var Carousel = function () { this.controls = new Controls(this); }; // ..
By defining Controls as a separate class, the "this" reference remains intact even within customized prototypes. However, this solution comes with the limitation of not allowing the implementation of Controls to be overridden.
Dependency Injection Solution:
To enable the overriding of Controls implementations, a dependency injection approach can be employed:
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); }; // .. var carousel = new Carousel(); carousel.addController(new Controls(carousel));
This solution provides flexibility by allowing the dynamic addition and modification of controllers, enabling the selective overriding of functionality in inherited classes.
The above is the detailed content of How Can I Organize JavaScript Prototypes While Preserving \'this\' References and Inheritance?. For more information, please follow other related articles on the PHP Chinese website!