简体   繁体   English

x时覆盖Javascript原型函数

[英]Javascript prototype function override when x

In my case, I'm using the Phaser framework. 就我而言,我正在使用Phaser框架。

So in this example I'm extending the Group class of phaser. 因此,在此示例中,我扩展了相位器的Group类。 Every 'actor' class (Sprite, Group, ...) calls upon the update() prototype every few miliseconds. 每个“演员”类(Sprite,Group等)每隔几毫秒就会调用一次update()原型。

My idea was to extend this function only when the application runs on a desktop (so not on a phone). 我的想法是仅在应用程序在台式机(而不是手机)上运行时才扩展此功能。

for example: 例如:

var MousePointer = function (game, parent, name) {
  Phaser.Group.call(this, game, parent, name);
  this.init();
};

MousePointer.prototype = Object.create(Phaser.Group.prototype);
MousePointer.prototype.constructor = MousePointer;

MousePointer.prototype.init = function () {
  // ... init
};

MousePointer.prototype.update = function () {
  // Do something when on desktop
};

I can't possibly use an if clausule in the update() function to check whether the player is on dekstop/tablet/phone. 我不可能在update()函数中使用if子句来检查播放器是否在桌面/平板电脑/电话上。 So is there a way to actually override the prototype on initialisation? 那么有没有办法在初始化时实际覆盖原型呢?

for example (pseudocode): 例如(伪代码):

if(onPhone)
  MousePointer.prototype.update = parent.prototype.update;
else
  MousePointer.prototype.update = this.update;

Well, you've kind of already written the answer for yourself, haven't you? 好吧,您已经为自己写下了答案,不是吗? This code (not inside the init method). 此代码(不在init方法内部)。

if(onPhone) {
  MousePointer.prototype.update = function(){//Phone implementation};
} else {
  MousePointer.prototype.update =  function(){//Other implementation};
}

I advise against starting off with the "regular" function and then potentially overriding it, since you're just declaring it for nothing. 我建议不要先使用“常规”功能,然后再覆盖它,因为您只是在声明它而已。

I think a better way to do this would be to write two different classes that shares the same parent, and then write different update() implementations for them. 我认为一种更好的方法是编写两个共享同一父级的不同类,然后为它们编写不同的update()实现。 Then you can just do something like: 然后,您可以执行以下操作:

if(phone) {
    var obj = new PhoneMousePointerObject();
} else {
    var obj = new DesktopMousePointerObject();
}
// ... later
obj.update()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM