JavaScript完成继承的方法

本文介绍JavaScript中使用原型实现继承的方法。通过具体实例展示了如何定义基类Item并利用原型链实现特殊子类specialItem的继承过程。子类不仅继承了基类的属性和方法,还能扩展自己的特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用原型

    <!DOCTYPE html>
<html>
<head>
    <title>JavaScript继承使用原型</title>
</head>
<body>
    <script type="text/javascript">
        function Item(color,count){
            this.color = color;
            this.count = count;
            if (color == undefined) { this.color = 'black'; }
            if (count == undefined) { this.count = 0; }
            this.log = function (){
                console.log('数量' + this.count + '颜色' + this.color);
            }

        }

        var blueObject = new Item("blue",5);
        console.log(blueObject);

        /*function specialItem(name){
            this.name = name;
            this.describe = function (){
                console.log(this.name + ":color = " + this.color);
            }
        }
        specialItem.prototype = new Item();//构造函数没有指定color和count属性,使用默认值*/
        //也可以通过修改specialItem构造函数来添加color和count属性,并将它们传递给Item构造函数
        function specialItem(name,color,count){
            Item.call(this, color,count);
            this.name = name;
            this.describe = function (){
                console.log(this.name + ":color = " + this.color);
            }
        }
        specialItem.prototype = new Item();

        //在创建一个specialItem对象后就可以访问log()和describe()方法
        var special = new specialItem("Widget","purple",4);
        special.log();
        special.describe();
        console.log(special);
    </script>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值