こんにちは、私は javascript oop に頭を悩ませようとしていますが、問題が発生しています。コンストラクター クラスを構築しています。クラスでプロパティを定義します。これらのプロパティを変更するメソッドを定義したいと思いますが、オブジェクトをインスタンス化するときプロパティが未定義であることをコンソールが教えてくれるメソッドを呼び出します。これはスコープと関係があるのではないかと思います。Google でいろいろ調べてみましたが、紹介記事は基本的にすべて同じです。
コードの簡略化されたバージョンを示します。私のコード例では、形状をキャンバス上で移動させたいと考えています。オブジェクト自体には、その動きを制御するメソッドがあります(今のところ)。オブジェクトをインスタンス化するとき、xy 座標を変更する moveRight メソッドを呼び出します。次に、毎秒、オブジェクトの x および y プロパティを呼び出す別の関数で画面にレンダリングします
//ここでオブジェクトを定義します
function Mechanoid(){
//object properties
this.life=100;
this.x=500;
this.y=200;
this.anArray=new Array(0, 0); //can i create an array like this? i know it works when called from outside the object
//object methods
this.moveAround=function(){
var clock=setInterval(Function () {
this.x=this.x+1; //console log says undefined
this.y=this.y+1;
this.anArray[0]=this.x; //console says cannot read propety of null
this.anArray[1]=this.y;
},1000);
}
}
//then instanciate
var mech=new Mechanoid;
mech.moveAround(); // calls method to change object properties
//A request for the x any y coordinates of mech object will be called in a render function where it
//will be drawn to the canvas.
オブジェクトメソッド内からプロパティにアクセスできない理由を誰か教えてもらえますか? それらにアクセスするにはどうすればよいですか?ありがとう...おそらく、構文にブラケットが欠落しているか、その場で書いたものがあります。元のコードに構文エラーがあるとは思いません。それが問題だとは思いません。