简体   繁体   English

JS在函数内部获取变量

[英]JS getting variable inside the function

I have a function to do something on onClick event. 我具有在onClick事件上执行某些操作的功能。

function onDocumentMouseUp( event ) {
    createsprite(clickedposition);
}

createsprite(clickedposition) {
  var sprite = JSONSPITE // this add correctly sprite to my scene;
  //// here timer function 1 sec
  setTimeout(function(){ remove(sprite); }, 1000);
}

Everything works correctly. 一切正常。 But when i click more than once, i have still my variable sprite as a last added one. 但是当我单击不止一次时,我仍然将变量sprite作为最后添加的变量。 (yes i know that is correct). (是的,我知道那是正确的)。 And logically remove() have affected only that last one. 从逻辑上讲, remove()仅影响了最后一个。

What is the correct solution to handle work with unknown amount of same variables. 解决未知数量相同变量的工作的正确解决方案是什么? Purpose it too remove each sprite after one second after click one by one in the order of creation. 目的是按创建顺序一秒钟单击一秒钟后,也删除每个精灵。

How can i reach only one variable in the same function, even when there are more variables with the same name on each function init. 即使在每个函数初始化中有更多具有相同名称的变量,我如何也只能在同一函数中获得一个变量。

You have defined sprite as a global variable. 您已将sprite定义为全局变量。 It will exist not only in that function, but is created on the window object. 它不仅会存在于该函数中,还会在window对象上创建。

If you want to remove only the sprite you created in that function, you should make it a variable 如果只想删除在该函数中创建的子画面,则应将其设为变量

var sprite = JSONSPITE; // typo?

This way, the scope of the sprite variable is just that function. 这样,sprite变量的作用域就是那个函数。

EDIT: OP has changed their question, making the previous explanation seem obsolete 编辑: OP改变了他们的问题,使以前的解释似乎过时了

If you want to create multiple sprites, and store them somewhere so you can access them before they are deleted, you might want to create an array of sprites. 如果要创建多个精灵,并将它们存储在某个位置,以便可以在删除它们之前对其进行访问,则可能要创建一个精灵数组。

sprites = [];

function onDocumentMouseUp( event ) {
    createsprite(clickedposition);
}

function createsprite(clickedposition) {
  sprites.push(JSONSPITE); // Adds the current sprite to the end of the array
  setTimeout(function(){
    var firstSprite = sprites.shift(); // Takes the first sprite out of the array
    remove(firstSprite); 
  }, 1000);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM