Javascript和原型制作程序

时间:2013-01-23 21:25:42

标签: javascript oop prototype

我正在尝试编写一个执行幻灯片放映的脚本。我可以用函数来做,但我想使用原型方法。我正在弄清楚的是程序。这是我试图做的事情

var displayVars = {
    slide: '',
    thumb: ''   
}

//setup display
display = function(slide,thumb) {

    displayVars.slide = $(slide);

    displayVars.thumb = $(thumb);

    // set slider width
}

display.prototype.play = function() {

    // move slide to this location

    display.hightlight();
}

display.prototype.hightlight = function() {

    // add border to element
}

$(function() {

    newdis = new display('.show-slide','.window-thumbs');

    displayVars.timer = setTimeout(newdis.play,500);

});

如果您在播放功能中注意到我想调用高亮方法。我真正想要的是每次调用play函数时都运行highlight函数。我无法理解如何做到这一点,因为“display”或“this”不会让我访问高亮功能。

1 个答案:

答案 0 :(得分:1)

问题不在于原型函数的内部,而在于设置超时处理程序的方式。

displayVars.timer = setTimeout(function() { newdis.play(); }, 500);

然后您就可以在“播放”功能中使用this

display.prototype.play = function() {

  // move slide to this location

  this.hightlight();
}

函数和任何类型的对象之间没有内在的“成员资格”关系。对象属性可以引用函数,但唯一的意思是通过对象属性引用进行函数调用时。由于你不是调用函数,而只是抓取对它的引用传递给“setTimeout()”,所以没有任何东西可以设置this的值。通过将其包装在通过对象引用显式调用“play”的匿名函数中,可以正确设置this

另一种方法是使用新版浏览器中的“bind()”函数:

displayVars.tinmer = setTimeout(newdis.play.bind(newdis), 500);

这将与匿名函数产生或多或少相同的效果(在大多数情况下会有一些额外的细微差别)。