JS面向对象教程:简单例子走进javascript面向对象入门
Javascript也可以面向对象编写,使用面向对象编程有什么好处,本站就不说了,网上一大把资料,现在就以简单的例子来入门JS面向对象编写,开始吧!下面是例子
<script type="text/javascript">
//类 - 动物
var animal = function(){
//生命
this.live = true
//性别
this.gender = "male";
}
//动物的行为方式
animal.prototype = {
//进食
dine:function(){
alert('进食');
},
//移动
move:function(){
alert('移动');
},
//繁殖
breed:function(){
alert('雌雄交配进行繁殖');
}
}
//类 - 人
var person = function(){
//继承动物的属性
animal.call(this);
//人还有人自己的一些属性
this.name = "Adam";
this.complexion = "white";
}
//继承动物的行为方法
person.prototype = new animal();
//改写人的行为方法
person.prototype.dine = function(){
(this.live)?alert("肤色:"+this.complexion+" ,性别:"+this.gender+" ,姓名:"+this.name+'\n用嘴吃东西!杂食!'):alert('不能进食!\nthis guy was dead!');
}
person.prototype.move = function(){
alert("肤色:"+this.complexion+" ,性别:"+this.gender+" ,姓名:"+this.name+'\n用两条腿直立行走!\n随着社会的进步,'+this.name+'可以乘坐不同的交通工具来代替行走!');
}
//实例
var pCharlie = new person();
pCharlie.name = "charlie";
pCharlie.complexion = "yellow";
pCharlie.dine();
pCharlie.move();
pCharlie.breed();
pCharlie.live = false;
pCharlie.dine();
</script>
- 上一篇:JS对数组取最大值与最小值的方法
- 下一篇:jquery仿百度图片幻灯浏览功能