JS 怎样模拟类的特性

本文介绍如何使用JavaScript实现类的模拟与继承,包括实现Dog继承Animal的过程,并演示了多态性和方法重写的实现方式。

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

function Animal(){}

function Dog(){}

1.实现 Dog 继承 Animal

Dog.prototype = Object.create(Animal.prototype)

背景知识:
    要实现 Dog 继承 Animal, 
    就是要实现 new Dog() instanceof Animal 为真
    就是要实现 new Dog().__proto__.__proto__ === Animal.prototype
    即实现 Animal.prototype 在 new Dog() 的原型链上
实现过程:
    根据js原型链的相关知识, 有 new Dog().__proto__ === Dog.prototype
    要实现继承, 就可以令 Dog.prototype.__proto__ === Animal.prototype
    也就是 Dog.prototype = Object.create(Animal.prototype)
复制代码
// 测试代码(直接在浏览器控制台中运行):
    
    function Animal(){}
    function Dog(){}
    Dog.prototype = Object.create(Animal.prototype);
    console.log(new Dog() instanceof Animal);//结果为 true
复制代码

2.实现 DogAnimal 类之间的多态,方法重写等

// 测试代码(直接在浏览器控制台中运行):

    function Animal(){}
    function Dog(){}
    Object.defineProperties(Animal.prototype,{
        name:{
            value(){
                return 'Animal';
            }
        },
        say:{
            value(){
                return 'I’m ' + this.name();
            }
        }
    });
    
    //子类Dog继承父类Animal中的方法
    Dog.prototype = Object.create(Animal.prototype);
    console.log(new Dog().say());//结果为 I’m Animal
    
    //子类Dog重写父类Animal的name方法
    Dog.prototype = Object.create(Animal.prototype,{
        name:{
            value(){
                return 'Dog';
            }
        }
    });
    console.log(new Dog().say());//结果为 I’m Dog
复制代码

3.完善类的模拟

// 测试代码(直接在浏览器控制台中运行):

    function Animal(){}
    function Dog(){}
    Dog.prototype = Object.create(Animal.prototype);
    console.log(Dog.prototype.constructor);//结果为 ƒ Animal(){}
    
    //上面的这个输出是不对的, 结果应该是 ƒ Dog(){}, 解决方法
     Dog.prototype = Object.create(Animal.prototype,{
        constructor:{
            value:Dog,
            enumerable:false
        } 
     });
     console.log(Dog.prototype.constructor);// 结果为 ƒ Dog(){}
复制代码

转载于:https://juejin.im/post/5ca20f32f265da308a2897f3

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值