在JavaScript中,prototype对象是实现面向对象的一个重要机制。
每个函数就是一个对象(Function),函数对象都有一个子对象 prototype对象,类是以函数的形式来定义的。prototype表示该函数的原型,也表示一个类的成员的集合。
定义一个名称为Mouse的函数(方法)
var Mouse = function(type){
//地鼠的具体dom元素,添加到页面上的
this.mouse = null;
//地鼠的编号
this.num = -1;
//地洞的编号(地鼠藏身在哪个洞)
this.hole = -1;
//初始化,type为地鼠类型,好与坏
this.init(type);
}
然后使用 prototype 属性来向函数(对象)添加属性
Mouse.prototype = {
//地鼠类型,好,坏,好的被杀,坏的被杀
mousetype: {
"good": "img/good.gif",
"bad": "img/bad.gif",
"goodkill":"img/goodkill.gif",
"badkill":"img/badkill.gif"
},
//初始化地鼠
init : function(type){
type = type || ‘good‘;
var _this = this;
//创建地鼠的dom元素
this.mouse = document.createElement("div");
//扩展属性--地鼠类型
this.mouse.mousetype = type;
//扩展类型--属否活着
this.mouse.islive = true;
this.mouse.style.cssText = ‘width:75px;height:100px;background:url(‘+this.mousetype[type]+‘);left:0;top:20px; position:relative;margin:auto;cursor:pointer;‘;
//绑定地鼠被点击事件
this.mouse.onclick = function(e){_this.beat(e);};
},
//地鼠被点中
beat : function(e){
if(this.mouse.islive){
this.mouse.islive = false;
this.onbeat();
this.mouse.style.background = "url("+this.mousetype[this.mouse.mousetype+"kill"]+")";
}
},
//地鼠的动画
animation : function(speed){
speed = speed == ‘fast‘?20:speed == ‘normal‘?30:50;
var obj = this.mouse,ost = obj.style,oTop = parseInt(ost.top,10),cut=5,_this = this;
//让地鼠从地洞冒出来
var show = function(top){
top = top-cut;
if(top >= -40){
ost.top = top + ‘px‘;
setTimeout(function(){show(top);},speed);
}
else
{
setTimeout(function(){hide(-40);},speed*10);
}
}
//隐藏地鼠
var hide = function(top){
top = top+cut;
if(top <= oTop){
ost.top = top + ‘px‘;
setTimeout(function(){hide(top);},speed);
}
else {
_this.reset();
}
}
show(oTop);
},
//重置地鼠,当地鼠滚回洞里的时候
reset : function(){
this.mouse.islive =true;
this.mouse.style.background = "url("+this.mousetype[this.mouse.mousetype]+")";
this.onend();
},
//扩展方法:地鼠被点中
onbeat : function(){},
//扩展方法:地鼠动画结束后
onend : function(){}
}
打地鼠游戏(2)之定义地鼠函数及函数原型 prototype
原文:https://www.cnblogs.com/boyzi/p/9964975.html