-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]);
}
質問このコードは動作していませんか? ")には、必要な動作、特定の問題またはエラー、およびその中で再現するのに必要な最短コードが含まれていなければなりません質問自体。明確な問題文がない質問は、他の読者にとって有用ではありません。参照:最小、完全、および検証可能な例を作成する方法。 – Amit
'.call()'は何もリンクしていません。関数を呼び出すだけで、関数の 'this'値として取得する最初の引数を設定します。あなたの 'intervalFunc'は何も返さないので、' shotsArray [0] .interval'を 'undefined'に設定するだけです。そして、あなたは 'this.move'を' setInterval() 'コールバックとして渡しています。これは' this'から 'move'を切り離すので、' move'は期待される 'this'値を持たないでしょう。 –
何をすればいいですか? –