JS面向物件--物件建立例項
阿新 • • 發佈:2018-12-19
一.此例項主要進行了面向物件以建構函式方式建立的簡單應用 html+css
<!--css部分-->
#wrap{width:500px;height:500px; border:1px solid red;position:relative;}
#target{position:absolute;width:100px;height:50px;background:green; left:200px; }
.bullet{width:30px; height:30px;background:red;position:absolute;bottom:0;left:235px; }
<!--html部分-->
<div id="wrap">
<div id="target"></div>
</div>
JS部分:
var wrap=document.querySelector("#wrap");
var target=document.querySelector("#target");
target.blood=100;//自定義子彈打擊物的血量屬性
target.isdie=false;//自定義當前子彈打擊物的是否存活屬性
//建立子彈函式
//每一個子彈新增一個計時器來進行移動
// function createBullets(parent){
// var bullet=document.createElement('div');
// bullet.className='bullet';
// parent.appendChild(bullet);
// }
//建構函式-->可以替換上面的建立子彈函式的寫法
function Bullets(parent){
this.tag=document.createElement('div');
//給標籤新增屬性名--即新增className
this.tag.className='bullet';
//要先進行標籤的建立和新增到父元素,然後獲取標籤的屬性值才可以獲得其中的值
this.add=function(){
parent.appendChild (this.tag);
}
this.move=function(){
var currentTop=this.tag.offsetTop;
var bullet=this.tag;
//在計時器中不要使用this,計時器是window的函式,如果使用this,指代的是window
var timer=setInterval(function(){
currentTop-=10;
if(currentTop<=target.offsetHeight)
{
target.blood-=100;//打擊物收到撞擊之後的掉血
clearInterval(timer);
bullet.remove();
//判斷當血量為0時的結果,並且根據打擊物的自定義屬性判斷當前如果打擊物的target.isdie屬性為true時不再走下面的if迴圈語句
if(target.blood<=0&&target.isdie==false)
{
target.isdie=true;
alert("game over!");
clearInterval(timer);
target.remove();//打擊物消失
}
}
bullet.style.top=currentTop+'px';
},100);
}
//如果想要實現標籤的建立並且新增到父元素超前於屬性值的獲得,可以在建構函式中就呼叫這個函式,即進行如下操作:
this.add();
}
wrap.onclick=function()
{var bullet=new Bullets(this);
bullet.move();}
例項及效果說明: 1.target自定義屬性的使用方法 此處進行了兩個自定義屬性的定義: target.blood=100;//自定義子彈打擊物的血量屬性 target.isdie=false;//自定義當前子彈打擊物的是否存活屬性 其中,被打擊物的isdie屬性最後與血量屬性的與判斷決定了打擊物最終的形態。 2.面向物件的建構函式的寫法以及其中的this的指代方法的使用