理解为什么我不能在Javascript中引用this.property“;“类”;
我有一个交互式视频播放器类的以下原型理解为什么我不能在Javascript中引用this.property“;“类”;,javascript,closures,html5-video,Javascript,Closures,Html5 Video,我有一个交互式视频播放器类的以下原型 // default constructor function BrightPlayer() { }; // prototypes for basic properties BrightPlayer.prototype.CurrentCourse = null; BrightPlayer.prototype.CurrentTopic = null; BrightPlayer.prototype.CurrentSubTopic
// 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>
虽然这是草率的,但我不想在每个脉冲上都进行元素查找。在尝试将Javascript类与C#类关联时,我肯定遗漏了一些东西。如果您能提供任何帮助,我们将不胜感激。由于使用了
此
,因此出现了问题
setInterval
定义为浏览器窗口
对象的功能。当从setInterval
调用时,this
的上下文是不同的,即是窗口
。因此,所有内容都在窗口中分配。属性window.VideoObject
不存在,因此您的代码无法工作
这个
在javascript中的工作方式与在C#中不同。在javascript中,此
受函数调用方式的约束(忽略箭头函数)。因此,在您的例子中,函数是从窗口
对象调用的
因此,要解决您的问题,您需要正确绑定this
。有不同的方法
将对该函数的引用存储在另一个变量self=this中代码>
使用bind
功能<代码>设置间隔(this.ApplicationPulse.bind(this),1000))
当您将this.ApplicationPulse
传递到setInterval
时,将使用不同的上下文调用它。您希望通过将ApplicationPulse
绑定到this
来明确定义将在其中运行的上下文:
BrightPlayer.prototype.Heartbeat = function () {
setInterval(this.ApplicationPulse.bind(this), 1000);
};
只需使用jQuery,就可以使用$(“#brightplayer视频”)获得视频播放器。jQuery非常高效,我认为你不会在浏览器中看到你的网页有任何减速。你是对的,只是Agalo比你快了1分钟,否则我会把你标记为正确的。非常感谢你把我介绍给。bind:)这把它修好了。谢谢你把我介绍给。bind!:)
BrightPlayer.prototype.Heartbeat = function () {
setInterval(this.ApplicationPulse, 1000);
};
BrightPlayer.prototype.Heartbeat = function () {
setInterval(this.ApplicationPulse.bind(this), 1000);
};