今天把代码写了,再议内容
<!DOCTYPE html>
<html>
<head>
<title>JS的继承</title>
</head>
<body>
<script type="text/javascript">
//父类
function Animal(name){
this.name=name;
this.sleep=function(){
console.log(this.name+" sleeping!");
}
}
Animal.prototype.eat = function(food) {
// body...
console.log(this.name+" is eating "+food);
};
//父类测试对象
var dog=new Animal("dog");
dog.sleep();
dog.eat("shit");
//===================继承方式==============
//原型链
function Cat(){
// this.sleep=function(){
// console.log("sleep");
// }
}
Cat.prototype=new Animal();//这个必须写在子类方法前
// Cat.prototype.say=function(){
// console.log("Cat say: "+this.name);
// }
Cat.prototype.name="cat";
Cat.prototype.say=function(){
console.log("Cat say: "+this.name);
}
Cat.prototype.sleep=function(){
console.log("sleep");
}
var cat=new Cat();
console.log(cat.name);
cat.say();
cat.sleep();
cat.eat("fish");
//构造继承
function Fish(name){
Animal.call(this);
this.name=name||"neemo";
Fish.prototype.say=function(){
console.log(this.name+" is speaking!");
}
this.speaking=function(){
console.log("speaking!");
}
}
var fish=new Fish();
fish.sleep();
fish.say();
fish.speaking();
//fish.eat("shit");不可以继承父类的原型方法
//实例继承
function Person(name){
var instance=new Animal();
instance.name=name||'Tom';
// this.say=function(){
// console.log(this.name+" is speaking!");
// }无法实现
return instance;
}
// Person.prototype.speaking=function(){
// console.log(this.name);
// } 这个也无法实现
var person=new Person(person);
console.log(person.name);
person.eat("shit");
//person.say();
//person.speaking();
console.log(person instanceof Animal);
console.log(person instanceof Person);
//拷贝继承
function Man(name){
var animal=new Animal();
for(var p in animal){
Man.prototype[p]=animal[p];
}
Man.prototype.name=name||"Tom";
}
var man=new Man();
console.log(man.name);
man.sleep();
//组合继承
function Woman(name){
Animal.call(this);
this.name=name||"Woman";
}
Woman.prototype=new Animal();
var woman=new Woman();
woman.eat("shit");
//寄生组合继承
function SB(name){
Animal.call(this);
this.name=name||"SB";
}
(function(){
var SBDog=function(){};
SBDog.prototype=Animal.prototype;
SB.prototype=new SBDog();
})();
var sb=new SB();
sb.eat("only shit!");
</script>
</body>
</html>