毫无疑问,我是新人,我很高兴加入这个伟大的社区。问题是,我有一个名为 Character 的 JavaScript 类,如下所示:
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
);
}
}
所以这是我的大问题,如何通过子匿名函数访问父方法?我整晚都在努力弄明白,但我找不到一些有用的信息,谢谢!
最佳答案
您需要将父级的 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
);
}
}
关于javascript - 在 JavaScript 类中调用父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12729824/