JS继承

来源:互联网 发布:java课程表管理系统 编辑:程序博客网 时间:2024/06/05 19:27
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>继承</title>
</head>


<body>
</body>
<script type="text/javascript">
<!--第一种继承call构造函数-->
/*
function monkey(_type,_home){
this.type = _type;
this.home = _home;
this.say = function(){
alert('猴子,住在'+this.home)
}
}
function magic_monkey (_type,_home,arr){
//在子类中调用父类的构造函数
monkey.call(this,_home,_type);

//第二种
//monkey.apply(this,[_type,_home]);
this.skill =arr;
}
var wukong = new magic_monkey('花果山','猴子',['七十二变','筋斗云']);
alert(wukong.skill);
alert(wukong.type);
alert(wukong.home);
wukong.say();
*/

//原型链的继承
/* function monkey(){}
monkey.prototype.type = '猴子';
monkey.prototype.say = function(){alert('我是快乐的小猴子')}

function magicmonkey(){}
//magicmonkey的prototype对象指向了monkey的一个实例
//相当于删除了prototype原始值给了一个monkey一个对象;
magicmonkey.prototype = new monkey();
//只能放在原型赋值之后
magicmonkey.prototype.skill = '法术';
//不能继承多个类,后边的会覆盖前边的。
var sunwukong = new magicmonkey();
alert(sunwukong.type);
sunwukong.say();
alert(sunwukong.skill);
*/
//混合模式
function monkey(_type,_home){
this.type = _type;
this.home = _home;
}
monkey.prototype.say = function(){
alert('猴子住在'+this.home)
}
function magicmonkey(_type,_home,_skill){
//y用对象冒充继承monkey里面的属性
monkey.call(this,_type,_home)
this.skill = _skill;
}
//用原型链继承monkey类的方法
magicmonkey.prototype = new monkey();
//子类方法对父类方法的覆盖
magicmonkey.prototype.say = function(){
alert('猴子会技能'+this.skill)
}
var wukong = new magicmonkey('猴子','花果山',['七十二变','筋斗云'])
alert(wukong.type);
alert(wukong.home);
wukong.say();
alert(wukong instanceof magicmonkey)
alert(wukong instanceof monkey)
</script>
</html>