【问题标题】:Why is object.function.this is undefined when using function.call?为什么使用function.call时object.function.this未定义?
【发布时间】:2017-01-18 12:22:59
【问题描述】:

我正在尝试使用调用来链接 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]);
 }

【问题讨论】:

  • 寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定的问题或错误以及在问题本身中重现它所需的最短代码。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建最小、完整和可验证的示例。
  • .call() 没有链接任何东西。它只是调用函数并将您获得的第一个参数设置为函数的this 值。您的intervalFunc 不会返回任何内容,因此您只需将shotsArray[0].interval 设置为undefined。而您将this.move 作为setInterval() 回调传递,它将movethis 分离,因此move 将不会具有预期的this 值。
  • 那我该怎么办?

标签: javascript object call


【解决方案1】:

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

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

使用 setInterval 时,您又失去了this,因此更改为:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-01
    • 2015-12-12
    • 1970-01-01
    • 2012-08-14
    • 2015-05-25
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多