나는 prototype과 jQuery 라이브러리를 사용했다. 그러나 나는 OOP JS를 더 광범위하게 배우고 싶다. 내가하고 싶은 일은 동시에 실행할 수있는 여러 개의 JS 개체를 만드는 것입니다. 여기에 나와있는 예제에서는 바운스하기 위해 7 개의 다른 상자를 만들고 싶습니다. 프로토 타입을 사용하여 개체를 여러 번 만드는 가장 좋은 방법을 읽었습니다. 다음은 내가 만든 작업 스크립트 예제입니다.자바에서 재사용 가능한 객체를 만드는 가장 좋은 방법
"this.int = setInterval (this.move, 20);"주석 처리를 제거하면 "this.box.style.left"를 찾을 수 없다는 오류가 발생합니다. 이동 기능에서. 바운스 개체에서 이동 기능이 손상된 것으로 보입니다. 나는이 일을하기 위해 내가 생각할 수있는 모든 것을 시도했다. 나는 int를 객체의 변수로 가질 필요가있어서 그것을 멈추게 할 수있다.
"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>