var Character = function()
{
// ..Some previous Properties / Methods (included one called "StareDown()")..
// And this method:
this.GrabDown = function()
{
Context.clearRect(0, 0, CanvasWidth, CanvasHeight);
//Context.fillRect(0, 0, CanvasWidth, CanvasHeight);
Context.drawImage(this.GrabbingDown, CharacterX, CharacterY, SpriteWidth, SpriteHeight);
window.setTimeout
(
function()
{
// Here is where I want to call the parent class method "StareDown()", but I don't know how.
},
250
);
}
}
所以这是我的一个大问题,如何通过该子匿名函数访问父方法?我一直想弄清楚整个晚上,但我找不到一些有用的信息,谢谢!
答案 0 :(得分:1)
您需要将父项的this
对象存储在变量中(假设您已将函数定义为this.StareDown = function () {...}
var Character = function()
{
// ..Some previous Properties / Methods (included one called "StareDown()")..
this.StareDown = function() {...}
var curCharacter = this;
this.GrabDown = function()
{
Context.clearRect(0, 0, CanvasWidth, CanvasHeight);
//Context.fillRect(0, 0, CanvasWidth, CanvasHeight);
Context.drawImage(this.GrabbingDown, CharacterX, CharacterY, SpriteWidth, SpriteHeight);
window.setTimeout
(
function()
{
// Here is where I want to call the parent class method "StareDown()", but I don't know how.
curCharacter.StareDown(...);
},
250
);
}
}
答案 1 :(得分:0)
您可以使用window.setTimeout(this.StareDown,250);
但请记住,该方法将在全局上下文中调用(即,这将指向window
,而不是调用Character
的{{1}}实例GrabDown
方法。
将该函数用作对象方法:
window.setTimeout((function(that)
{
return function()
{
return that.StareDown();
}
})(this),250);
应该有效。这可能相当冗长,或许可以查看call
,apply
,尤其是bind
的MDN文档可能会很有用
答案 2 :(得分:0)
这就是我要做的事情:
var Character = function () {
this.GrabDown = function () {
setTimeout(function () {
// call this.StareDown in here
}.bind(this), 250);
};
};
这是有效的,因为我们将this
指针绑定到传递给FunctionExpression
的匿名setTimeout
。因此,它可以像正常的方法一样使用。