为什么在使用function.call?

时间:2016-09-10 14:27:59

标签: javascript object call

我正在尝试使用call来链接setInterval函数(intervalFunc)和move()对象中包含的函数。每当我使用它时,我得到以下

error:"shooter2.js:46 Uncaught TypeError: Cannot read property 'style' of null" 

this.id显然未定义,但我无法弄明白为什么。

 //SPACESHIP
 var spaceShip=
{
  width:20,
  height:35,
  x:700,
  y:665
}

// Set SpaceShip start position
document.getElementById("dv_spaceShip").style.left=spaceShip.x+"px";
document.getElementById("dv_spaceShip").style.top=spaceShip.y+"px";




// SHOTS
var shotsArray = [];
var shotCount=-1;
function shotConstruct(id)
{
  this.id=id,
  this.interval;
 this.createHtml=function(){

// Creating a new div and attaching it to the dv_global
var setDiv=document.createElement("div");
var setId=setDiv.setAttribute("id",this.id);
document.getElementById("dv_global").appendChild(setDiv);

var shotId= document.getElementById(this.id);
console.log("shotId="+shotId);
// Creating physical elements
shotId.style.width=this.width+"px";
shotId.style.height=this.height+"px";
shotId.style.backgroundColor=this.BGcolor;
shotId.style.position="absolute";
shotId.style.left=spaceShip.x+3.5+"px";
shotId.style.top=this.y+"px";
   }

  //Moving the shot
  this.move=function(){
  console.log("this.id"+this.id);
  document.getElementById(this.id).style.top=50+"px";
    }

    }

// Properties and methods shared by all shots
shotConstruct.prototype.width=10;
shotConstruct.prototype.height=10;
shotConstruct.prototype.speed=10;
shotConstruct.prototype.BGcolor="#000099";
shotConstruct.prototype.y=655;



    function intervalFunc(){
    setInterval(this.move,2000);
    }


  function shoot()
  { 
  // Clears the array containing all shots, may be optionnal
  shotsArray=[];
  shotCount+=1;
  shotsArray.push("Shot"+shotCount);
  //console.log(shotsArray[0]);
  shotsArray[0]=new shotConstruct(shotsArray[0]);
   //console.log(shotsArray[0]);
   console.log(shotsArray[0]);
  // Create html elements for each shot.
   shotsArray[0].createHtml();
  //shotsArray[0].move();
  shotsArray[0].interval=intervalFunc.call(shotsArray[0]);
 }

1 个答案:

答案 0 :(得分:0)

call()第一个参数是执行函数的this

intervalFunc.call(this, shotsArray[0]);

使用setInterval时,您再次失去this,因此请更改为:

setInterval(this.move.bind(this), 2000);