在保留对象引用和继承的同时组织原型 javascript [英] Organize prototype javascript while perserving object reference and inheritance
问题描述
我使用 JavaScript 原型和继承构建了一个大型应用程序.但是我很难组织我的代码.例如,我有一个类轮播,它有很多这样的功能:
I have built a large application using JavaScript prototype and inheritance. But I am having a hard time organizing my code. For example I have a class carousel which has many functions like this:
Carousel.prototype.next = function () {...}
Carousel.prototype.prev = function () {..}
Carousel.prototype.bindControls = function () {..}
我想像这样组织我的代码:
I would like to organize my code like this :
Carousel.prototype.controls = {
next: function () { ... } ,
prev: function() { ... },
bindControls: function () { .. }
}
但这会导致this"的值丢失.我可以使用全局实例跟踪它,但是当类被继承时这会导致问题,例如在另一个文件中我有类似的东西来覆盖父类
But this will cause the value of "this" being lost. I can keep track of it using a global instance but this will cause problems when the class is inherited for example In another file I have something like this to override parent class
BigCarousel.prototype.next = function () {...}
我的继承是这样完成的:
My inheritance is done like this:
Function.prototype.inheritsFrom = function (parentClass) {
if (parentClass.constructor === Function) {
//Normal Inheritance
this.prototype = $.extend(this.prototype , new parentClass);
this.prototype.constructor = this;
this.prototype.parent = parentClass.prototype;
}
else {
//Pure Virtual Inheritance
this.prototype = $.extend(this.prototype, parentClass);
this.prototype.constructor = this;
this.prototype.parent = parentClass;
}
return this;
};
所以我可以这样做:
BigCarousel.inheritsFrom(Carousel)
有谁知道我如何解决这个"值?
Does anyone know how can I work around the "this" value ?
推荐答案
你可以让 Controls
成为它自己的一个类:
You could make Controls
a class of it's own:
var Controls = function (controllable_object) {
this.ref = controllable_object;
};
Controls.prototype.next = function () {
this.ref.foo();
}
// ..
var Carousel = function () {
this.controls = new Controls(this);
};
// ..
虽然这不允许您覆盖 Controls
的实现.随着更多的依赖注入,你会得到类似的东西:
This doesn't allow you to override the implementation of Controls
though. With more dependency injection you'd get something like:
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));
这篇关于在保留对象引用和继承的同时组织原型 javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!