我使用JavaScript原型和继承构建了一个大型应用程序.但我很难组织我的代码.例如,我有一个类旋转木马,它有许多这样的功能:
Carousel.prototype.next = function () {...}
Carousel.prototype.prev = function () {..}
Carousel.prototype.bindControls = function () {..}
Run Code Online (Sandbox Code Playgroud)
我想像这样组织我的代码:
Carousel.prototype.controls = {
next: function () { ... } ,
prev: function() { ... },
bindControls: function () { .. }
}
Run Code Online (Sandbox Code Playgroud)
但这会导致"这个"的价值丢失.我可以使用全局实例跟踪它但这会在继承类时导致问题例如在另一个文件中我有类似的东西来覆盖父类
BigCarousel.prototype.next = function () {...}
Run Code Online (Sandbox Code Playgroud)
我的继承是这样完成的:
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); …Run Code Online (Sandbox Code Playgroud) 如何才能缓存最顶层的范围,以便以后在原型中更深入地使用,如下所示:
var Game = function(id){
this.id = id;
};
Game.prototype = {
board : {
init: function(){
// obviously "this" isn't the instance itself, but will be "board"
console.log(this.id);
}
}
}
var game = new Game('123');
game.board.init(); // should output "123"
Run Code Online (Sandbox Code Playgroud)
那么现在我考虑一下,我可以使用apply/ call并传递上下文...
game.board.init.apply(game);
Run Code Online (Sandbox Code Playgroud)