B3-JS面向对象-继承

继承

方法一 空对象作为中介

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的伙伴们“挑毛病”“提意见”,当然了也欢迎各种表扬奥~(比心,比心)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值