我使用 JavaScript 原型(prototype)和继承构建了一个大型应用程序。 但是我很难组织我的代码。 例如,我有一个类轮播,它有很多这样的功能:
Carousel.prototype.next = function () {...}
Carousel.prototype.prev = function () {..}
Carousel.prototype.bindControls = function () {..}
我想这样组织我的代码:
Carousel.prototype.controls = {
next: function () { ... } ,
prev: function() { ... },
bindControls: function () { .. }
}
但这会导致“this”的值丢失。我可以使用全局实例跟踪它,但这会在类被继承时导致问题,例如在另一个文件中,我有类似这样的东西来覆盖父类
BigCarousel.prototype.next = function () {...}
我的继承是这样完成的:
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)
有谁知道我该如何解决“这个”值?
最佳答案
你可以让 Controls
成为它自己的一个类:
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
的实现。随着更多的依赖注入(inject),你会得到类似的东西:
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 - 在保留对象引用和继承的同时组织原型(prototype) javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15884096/