-1
setInterval
함수 (intervalFunc)와 move()
함수를 개체에 포함 된 호출을 사용하여 연결하려고합니다. 내가 그것을 사용할 때마다 나는 다음과 같은function.call을 사용할 때 object.function.this가 정의되지 않은 이유는 무엇입니까?
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]);
}
질문 이 코드가 작동하지 않습니까? ") 원하는 동작, 특정 문제 또는 오류 및 해당 코드를 재생산하는 데 필요한 가장 짧은 코드가 포함되어야합니다. 질문 자체. 분명한 문제 성명이없는 질문은 다른 독자에게 유용하지 않습니다. See : 최소한의 완전하고 검증 가능한 예제를 만드는 방법. – Amit
'.call()'은 아무 것도 연결하지 않습니다. 그냥 함수를 호출하고 함수의 'this'값으로 얻는 첫 번째 인수를 설정합니다. 'intervalFunc'는 아무 것도 반환하지 않으므로 단지'shotsArray [0] .interval'을'undefined'로 설정하는 것입니다. 그리고'this.move'를'setInterval()'콜백으로 전달하면'this'에서'move'가 분리되어'move'는 예상 된'this' 값을 갖지 않을 것입니다. –
그럼 어떻게해야합니까? –