[英]Why I couldn't access object's property?
I'm trying to manipulate Vec2 object's properties (x and y) in onDocumentKeyDown()
function which is in event.js.我正在尝试在 event.js 中的onDocumentKeyDown()
function 中操作 Vec2 对象的属性(x 和 y)。 Why I couldn't access vec2's property in onDocumentKeyDown()
function?为什么我无法在onDocumentKeyDown()
function 中访问 vec2 的属性?
file: event.js文件:event.js
function onDocumentKeyDown(event, vec2){
var x_p = vec2.x; // Uncaught TypeError: Cannot read property 'x' of undefined
var y_p = vec2.y;
...
file: app.js文件:app.js
function init(){
...
var vec2 = new Vec2(0,0);
function animate (time) {
...
document.addEventListener("keydown", onDocumentKeyDown, false);
vec2 = onDocumentKeyDown(event, vec2);
obj.move(vec2);
...
startTime = time;
window.requestAnimationFrame(animate);
}
animate(0);
}
Vec2 class (Vec2.js): Vec2 class (Vec2.js):
class Vec2{
x;
y;
constructor(x, y){
this.x = x;
this.y = y;
}
...
}
index.html:索引.html:
.....
<script src="vec2.js"></script>
<script src="lib.js"></script>
<script src="event.js"></script>
<script src="app.js"></script>
</body>
When you addEventListener as onDocumentKeyDown
it is just passed an event value and not the vec2
as argument.当您 addEventListener 作为onDocumentKeyDown
时,它只是传递了一个事件值,而不是vec2
作为参数。
You can use .bind
method to pass on the custom arguments.您可以使用.bind
方法传递自定义 arguments。 However you would need to change the order in which you receive arguments like但是,您需要更改收到 arguments 的顺序,例如
function onDocumentKeyDown(vec2, event){
var x_p = vec2.x;
var y_p = vec2.y;
...
}
function init(){
...
var vec2 = new Vec2(0,0);
function animate (time) {
...
const fn = onDocumentKeyDown.bind(this, vec2);
document.addEventListener("keydown", fn , false);
vec2 = onDocumentKeyDown(vec2, event);
obj.move(vec2);
...
startTime = time;
window.requestAnimationFrame(animate);
}
animate(0);
}
Since you wouldn't want to change the argument order to onDocumentKeyDown, you can make use of arrow function由于您不想将参数顺序更改为 onDocumentKeyDown,因此可以使用箭头 function
function onDocumentKeyDown(event, vec2){
var x_p = vec2.x;
var y_p = vec2.y;
...
}
function init(){
...
var vec2 = new Vec2(0,0);
function animate (time) {
...
const fn = (event) => onDocumentKeyDown(event, vec2);
document.addEventListener("keydown", fn , false);
vec2 = onDocumentKeyDown(vec2, event);
obj.move(vec2);
...
startTime = time;
window.requestAnimationFrame(animate);
}
animate(0);
}
PS Since you need to pass the same instance of function to removeEventListener that you passed to addEventListener, we can store the binded function to a seperate variable PS 由于您需要将相同的 function 实例传递给您传递给 addEventListener 的 removeEventListener,我们可以将绑定的 function 存储到单独的变量中
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.