在持久化对象引用和继承的同时组织原型javascript [英] Organize prototype javascript while perserving object reference and inheritance

查看:126
本文介绍了在持久化对象引用和继承的同时组织原型javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用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 ?

推荐答案

你可以让控制一类它自己:

var Controls = function (controllable_object) {
    this.ref = controllable_object;
};
Controls.prototype.next = function () {
    this.ref.foo();
}
// ..

var Carousel = function () {
    this.controls = new Controls(this);
};
// ..

这不允许你覆盖<$的实现c $ c>控制但是。随着更多的依赖注入你会得到类似的东西:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆