Javascript 继承 - 调用子方法总是调用父方法

Javascript inheritance - call to child method always invokes method of parent

这是我第一次在 Javascript 中使用继承。我在做一件事的对象 "LatchOn" 和具有基础 class 的所有功能的对象 "LatchOnSlider" 之间有一个 class 逻辑父子关系,然后是一些更多的。精简代码:

/*creating the instances*/

var latchon = NewLatchOn();   //arguments not important for this
var latchonslider = NewLatchOnSlider();

//factory function
function NewLatchOn(element_id, container_id, screenpos, release)
{
 var newLatchOn = new LatchOn(element_id, container_id, screenpos, release);
 newLatchOn.startTimer();
}

function LatchOn(element_id, container_id, screenpos, release)
{
  //initialise stuff
}


LatchOn.prototype.startTimer = function()
{
 var that = this;     
 setInterval(function(){that.checkPos()}, 10);
}

LatchOn.prototype.checkPos = function()
{
    //do stuff
}






LatchOnSlider.prototype.constructor = LatchOnSlider;

//factory function
function NewLatchOnSlider(element_id, container_id, image_class, screenpos)
{
 LatchOnSlider.prototype = Object.create(LatchOn.prototype);
 var newSlider = new LatchOnSlider(element_id, container_id, image_class, screenpos);
 newSlider.startTimer();
 return newSlider;
}

function LatchOnSlider(element_id, container_id, image_class, screenpos)
{
 LatchOn.call(this, element_id, container_id, screenpos, "CONTAINER");
 
    //initialise own stuff
}


LatchOnSlider.prototype.startTimer = function()
{
 var that = this;     
 setInterval(function(){that.checkPos()}, 10);
}

/*keeps track of when to switch images*/
LatchOnSlider.prototype.checkPos = function()       
{
 alert("child process called");
}

对象必须监听浏览器中的滚动位置并根据该信息采取行动。所以他们有一个定时器运行ning。但是对于继承对象的两个定时器 运行 来说,这不是最佳选择,我想我可以 运行 一个调用子对象函数的定时器,它将调用基函数和然后做它自己的事情(代码中还没有调用基本函数。我还没有那么远......)。

为了不必为每个实例单独启动计时器,我创建了工厂函数来初始化对象并启动它们的计时器。这就是我被困的地方。无论我做什么,如果我在 LatchOnSlider 对象上调用 startTimer,则会调用父对象的函数。我已经浏览了至少五个不同的教程并尝试了所有的语法变体,但没有解决问题。我已经在 firebug 中完成了它,到那时为止该过程按预期工作。 LatchOnSlider 的构造函数被调用,基础对象的构造函数从那里被调用,一切都正确初始化,就在 LatchOnSlider.startTimer() 被调用时, LatchOn.startTimer() 被执行。我完全不知道此时可能是什么问题。

这一行是问题所在:

function NewLatchOnSlider(element_id, container_id, image_class, screenpos) {
  LatchOnSlider.prototype = Object.create(LatchOn.prototype);

在这里,每次创建实例时,您都在创建一个新的原型对象。这些新原型没有您之前在 "old" LatchOnSlider.prototype 上分配的方法,并且您的实例不会继承它们 - 只有 LatchOn.prototype 间接方法。

您需要将构造函数声明和原型初始化与工厂函数分开:

function NewLatchOnSlider(element_id, container_id, image_class, screenpos) {
    var newSlider = new LatchOnSlider(element_id, container_id, image_class, screenpos);
    newSlider.startTimer();
    return newSlider;
}

function LatchOnSlider(element_id, container_id, image_class, screenpos) {
    LatchOn.call(this, element_id, container_id, screenpos, "CONTAINER");
    // initialise own stuff
}

LatchOnSlider.prototype = Object.create(LatchOn.prototype);
LatchOnSlider.prototype.constructor = LatchOnSlider;
LatchOnSlider.prototype.startTimer = function() { … }
LatchOnSlider.prototype.…

对于作业,顺序很重要:-)