我有一个交互式视频播放器类的以下Protoype ...
// default constructor
function BrightPlayer() { };
// prototypes for basic properties
BrightPlayer.prototype.CurrentCourse = null;
BrightPlayer.prototype.CurrentTopic = null;
BrightPlayer.prototype.CurrentSubTopic = null;
BrightPlayer.prototype.CurrentTimestamp = null;
BrightPlayer.prototype.VideoSelector = null;
BrightPlayer.prototype.VideoObject = null;
BrightPlayer.prototype.Heartbeat = function () {
setInterval(this.ApplicationPulse, 1000);
};
BrightPlayer.prototype.ApplicationPulse = function () {
// javascript errors occurs on the next line.
// VideoObject is undefined.
this.CurrentTimestamp = this.VideoObject.currentTime;
console.log('pulse....');
};
BrightPlayer.prototype.Init = function () {
// My thoughts were that the following line would initialize
// the VideoObject in this instance, and subsequent calls
// in the Application Pulse would have this reference, but it's not working
this.VideoObject = document.getElementById("brightplayer-video");
this.Heartbeat();
};
该类已实例化,Init从我的主HTML页面启动。
<script>
var Aplayer = new BrightPlayer();
Aplayer.Init();
</script>
但是,如果我添加这个.VideoObject = document.getElementById(“brightplayer-video”);在ApplicationPulse函数内部,它可以工作。
即。
BrightPlayer.prototype.ApplicationPulse = function () {
this.VideoObject = document.getElementById("brightplayer-video");
this.CurrentTimestamp = this.VideoObject.currentTime;
console.log('pulse....');
};
虽然这很草率,但我不想在每个脉冲上进行元素查找。在尝试将Javascript类与C#类相关联时,我必须遗漏一些东西。您将给予的任何帮助将不胜感激。
答案 0 :(得分:0)
由于使用了this
,问题就出现了。
setInterval
被定义为浏览器window
对象的函数。从this
调用时setInterval
的上下文不同,即window
。因此,所有内容都会在window
上分配。属性window.VideoObject
不存在,因此您的代码不起作用。
this
与C#中的工作方式不同。在javascript中,this
受如何调用函数(忽略箭头函数)的约束。因此,在您的情况下,从window
对象调用该函数。
因此,要解决您的问题,您需要正确绑定this
。有不同的方式。
self = this;
bind
功能。 setInterval(this.ApplicationPulse.bind(this), 1000))
答案 1 :(得分:0)
BrightPlayer.prototype.Heartbeat = function () {
setInterval(this.ApplicationPulse, 1000);
};
当您将this.ApplicationPulse
传递给setInterval
时,会使用不同的上下文调用它。您希望通过将ApplicationPulse
绑定到this
来明确定义BrightPlayer.prototype.Heartbeat = function () {
setInterval(this.ApplicationPulse.bind(this), 1000);
};
将运行的上下文:
onclick