
[英]Javascript - Class - Method Returning Undefined When Calling Constructor Property
[英]Javascript calling method in same class comes undefined?
所以我對js來說還比較陌生,因此我試圖在我的“ recordInputs”類中調用方法“ lerp”。 recordInputs類在其他地方調用,並且無需lerp函數即可正常工作。 問題在於,當playerImage.x / y等於lerp函數時,會出現控制台錯誤,並指出'lerp'方法未定義...
這是代碼:
class PlayerMoveClass {
lerp(start, end, time) {
return (1-time) * start + time * end;
}
RecordInputs(event) {
currentXPos = playerImage.x;
currentYPos = playerImage.y;
xMousePosition = event.clientX;
yMousePosition = event.clientY;
playerImage.x = lerp(currentXPos, xMousePosition, 0.1);
playerImage.y = lerp(currentYPos, yMousePosition, 0.1);
console.log("X POS: " + playerImage.x + " Y POS: " + playerImage.y);
}
}
在此先感謝任何可以提供幫助的人!
引用類成員需要使用this
關鍵字。
在您的情況下:
playerImage.x = this.lerp(currentXPos, xMousePosition, 0.1);
playerImage.y = this.lerp(currentYPos, yMousePosition, 0.1);
如果您將RecordInputs
用作事件偵聽器(如注釋中所建議),則可能還需要將此構造函數添加到您的類中才能正確綁定this
:
constructor() {
this.RecordInputs = this.RecordInputs.bind(this);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.