继承
方法一 空对象作为中介
1:普通
语法:
var F = function(){};
F.prototype = Father.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
var 变量名 = new Child(参数);
变量名.属性名/属性名()
2:封装为函数
语法:
function extend(Child,Father){
var F = function(){};
F.prototype = Father.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
extend(子类,父类);//调用
var 变量名 = new Child(参数);
变量名.属性名/属性名()
方法二 原型链与构造函数结合的组合继承
原型链
语法:
Child.prototype = new Father();
Child.prototype.constructor = Child;
构造函数
子类函数中{
//或者Father.apply(this,[参数1,参数2])
Father.call(this,参数1,参数2)
***//相关代码;
}
组合
示例
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
function Animal(color,name,age){
this.color = color;
this.name = name;
this.age = age;
}
function Poultry(color,name,age,leg){
Animal.call(this,color,name,age);
this.leg = leg;
}
Poultry.prototype.show = function(){
document.write("我是一个" + this.color + "的" + this.name + ",我已经" + this.age + "岁了,我有" + this.leg + "条腿<br/>")
}
var dog = new Poultry("灰色","小狗狗",1,4);
var cat = new Poultry("白色","茶杯猫",2,4)
var chichen = new Poultry("红色","小母鸡",1,2)
dog.show()
cat.show()
chichen.show()
</script>
样式如下:
今天的分享就是这些啦,欢迎正在学习web的伙伴们“挑毛病”“提意见”,当然了也欢迎各种表扬奥~(比心,比心)