我使用原型和jQuery庫。不過我想更廣泛地學習OOP JS。我想要做的事情是創建一個JS對象的多個實例同時運行。在我正在這裏工作的例子中,我想創建7個不同的盒子來反彈。我閱讀了使用原型多次創建對象的最佳方法。這是我創建的一個工作腳本示例。在Javascript中創建可重用對象的最佳方式
我碰到的問題是如果取消註釋「this.int = setInterval(this.move,20);」,我得到一個錯誤,說它找不到「this.box.style.left」在移動功能中。看起來移動功能從反彈對象中斷開。我嘗試了所有我能想到的工作。我需要有int作爲對象的變量,所以我可以做一個停止函數來殺死它。
like「bounce.prototype.stop = function(){clearInterval(this.int);});」
HTML
<body onload="dothis()">
<div id="case">
<div class="boxclass" id="box1">BOX</div>
</div>
</body>
CSS
<style type="text/css">
body {
background-color: #3F9;
text-align: center;
margin: 0px;
padding: 0px;
}
#case {
background-color: #FFF;
height: 240px;
width: 480px;
margin-right: auto;
margin-bottom: 72px;
position: relative;
margin-top: 72px;
margin-left: auto;
}
.boxclass {
background-color: #F96;
height: 36px;
width: 36px;
position: absolute;
}
</style>
JAVASCRIPT
<script type="text/javascript">
function bounce(frame,box,speed,x,y) {
this.speed = speed;
this.frame = frame;
this.box = box;
this.fw = frame.offsetWidth;
this.fh = frame.offsetHeight;
this.bx = x;
this.by = y
this.int = '';
return this;
}
bounce.prototype.position = function() {
if (this.box.offsetLeft <= 0 && this.bx < 0) {
console.log('LEFT');
this.bx = -1 * this.bx;
}
if ((this.box.offsetLeft + this.box.offsetWidth) >= this.frame.offsetWidth) {
console.log('RIGHT');
this.bx = -1 * this.bx;
}
if (this.box.offsetTop <= 0 && this.by < 0) {
console.log('TOP');
this.y = -1 * this.y;
}
if ((this.box.offsetTop + this.box.offsetHeight) >= this.frame.offsetHeight) {
console.log('BOTTOM');
this.y = -1 * this.y;
}
return this;
}
bounce.prototype.move = function() {
this.box.style.left = this.box.offsetLeft + this.bx+"px";
this.box.style.top = this.box.offsetTop + this.by+"px";
//this.int = setInterval(this.move,20);
}
function dothis() {
bn1 = new bounce(document.getElementById('case'), document.getElementById('box1'), 10,20,30).position();
bn1.move();
}
</script>