递归mainloop使对象未定义

时间:2015-03-19 13:23:58

标签: javascript recursion this

我认为我已经误解了关键字'这个'的用法。在javascript中。我无法理解为什么" this.box1"第二次执行mainloop时,从[object Object]更改为[object HTMLDivElement],以及为什么会抛出TypeError?

" BOX1"是html代码中div元素的html id,形状像一个正方形。

function GeoObject(id){
    this.name = id;
    this.object = document.getElementById(id);
    this.objectStyle = window.getComputedStyle(this.object);
    this.heightCenter = parseInt(this.objectStyle.height) / 2;
    this.widthCenter = parseInt(this.objectStyle.width) / 2;
    console.log(this.name + "'s heightCenter: " + this.heightCenter);
    console.log(this.name + "'s widthCenter: " + this.widthCenter);
}

GeoObject.prototype.setMiddle = function(){
    //console.log("In setmiddle, this.heightCenter: " + this.heightCenter);
    this.object.style.top = (window.innerHeight / 2) - this.heightCenter + "px";
    this.object.style.left = (window.innerWidth / 2) - this.widthCenter + "px";
    console.log(this.name + "'s top: " + this.object.style.top);
    console.log(this.name + "'s left: " + this.object.style.left);
}

function PlayGround(){
    this.box1 = new GeoObject("box1");
    console.log("PlayGround.box1 object: " + this.box1.object);
    console.log("PlayGround.box1 objectStyle " + this.box1.objectStyle);
}


PlayGround.prototype.update = function(){
    console.log("this.box1.object: " + this.box1.object);
    this.box1.setMiddle();
    that = this;
    requestAnimationFrame(that.update);
};

P1 = new PlayGround();
//console.log("P1.box1.object: " + P1.box1.object);
P1.update();

输出:

"box1's heightCenter:" 100                                main.js (row 21)
"box1's widthCenter:" 100                                 main.js (row 22)
"PlayGround.box1 object:" [object HTMLDivElement]         main.js (row 35)
"PlayGround.box1 objectStyle" [object CSS2Properties]     main.js (row 36)
"this.box1:" [object Object]                              main.js (row 41)
"box1's top": 197px                                       main.js (row 29)
"box1's left": 583px                                      main.js (row 30)
"this.box1:" [object HTMLDivElement]                      main.js (row 41)

TypeError: this.box1.setMiddle is not a function        main.js (row 42, col 4)
this.box1.setMiddle();

0 个答案:

没有答案
相关问题