在Javascript中创建可重用对象的最佳方法

时间:2012-10-28 04:37:33

标签: javascript oop

我使用了原型和jQuery库。但是我想更广泛地学习OOP JS。我想要做的事情是创建一个JS对象的多个实例同时运行。在我正在使用的示例中,我想创建7个不同的盒子来反弹。我阅读了使用原型多次创建对象的最佳方法。这是我创建的一个工作脚本示例。

我遇到的问题是如果取消注释“this.int = setInterval(this.move,20);”,我得到一个错误,说它无法找到“this.box.style.left”in移动功能。似乎移动功能从反弹对象中被破坏了。我已经尝试了一切我能想到的工作。我需要将int作为对象的变量,这样我就可以使用stop函数来终止它。

喜欢“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>

1 个答案:

答案 0 :(得分:2)

当你调用this.move时,你错过了上下文。 基本上,在JS中你需要传递上下文来调用方法,否则this.move将在另一个上下文中运行。

您可以将此指针缓存在SetInterval之外,并使用它来调用它:

setInterval(function(context) {
    return function() {context.move(); } 
} )(this), 20);

或者这个:

var that = this;
setInterval(function(){
    that.move();
}, 20);
相关问题