index.html
<script type="module">
import Main from './js/main_oop.js';
new Main()
</script>
main_oop.js
import Rect from "./rect_oop.js";
export default class Main {
arr = [];
constructor() {
for (var i = 0; i < 10; i++) {
let rect = new Rect();
this.arr.push(rect);
rect.appendTo(document.body);
}
setInterval(()=>{
this.animation()
}, 16);
}
animation() {
for (var i = 0; i < this.arr.length; i++) {
this.arr[i].update();
}
}
}
rect_oop.js
export default class rect {
speed = 2;
bool = false;
x = 0;
constructor(){
this.elem = this.createElem();
}
createElem(){
if(this.elem) return this.elem;
let div = document.createElement('div');
Object.assign(div.style,{
width:'50px',
height:'50px',
backgroundColor:'red',
position:'absolute',
left:'0px'
})
div.addEventListener('click',e=>{
this.clickHandler()
})
return div;
}
appendTo(parent){
parent.appendChild(this.elem);
}
update(){
if(!this.bool) return;
this.x += this.speed;
this.elem.style.left = this.x + 'px';
}
clickHandler(){
this.bool = !this.bool;
}
}