美文网首页
Javascript 面向对象(ES5继承)

Javascript 面向对象(ES5继承)

作者: 龚达耶 | 来源:发表于2019-10-12 03:18 被阅读0次

ES5继承

在ES5中继承是通过原型链来继承的。

我们都知道每个构造函数都有有一个原型对象,原型对象都包含一个指向构造函数的指针,而是列都包含一个指向原型对象的指针。

        function DaGe() {
            this.type = 'Da Ge'
            this.beat = ()=>{
                console.log('Da Ge Hao')
            }
        }
        DaGe.prototype.bart = function () {
            return this.type;
        }

        function ErGe() {
            this.type = 'Er Ge'
            
        }
        ErGe.prototype.bart2 = function () {
            return this.type;
        }

        ErGe.prototype = new DaGe();
       
        const instance = new ErGe();

        console.log(instance.bart()); // 继承prototype返回type因为ErGe里有type所以为Er Ge
        console.log(instance.beat()); // 继承prototype返回type因为ErGe里没有beat()所以为Da Ge Hao
        console.log(instance.bart2()); // 报错因为此时指向DaGe并没有指向ErGe所以bart2并没有

上面的代码看似没有问题其实还是有一个不容易发现的问题。

当我们来判断prototype对象的constructor属性时出现了问题。

//在const instance = new ErGe(); 后添加
console.log(ErGe.prototype.constructor === DaGe) // true 

//因为已经继承了所以constructor指向了DaGe但是是有问题的

// 明明instance是通过构造函数ErGe生成的
所以我们必须在每一次替换了prototype对象

//我们要重新指回原构造函数
ErGe.prototype.constructor  = ErGe; 

最终代码如下

 function DaGe() {
            this.type = 'Da Ge'
            this.beat = ()=>{
                console.log('Da Ge Hao')
            }
        }
        DaGe.prototype.bart = function () {
            return this.type;
        }

        function ErGe() {
            this.type = 'Er Ge'
            
        }
        ErGe.prototype.bart2 = function () {
            return this.type;
        }

        ErGe.prototype = new DaGe();
        ErGe.prototype.constructor  = ErGe; 
        const instance = new ErGe();
        console.log(ErGe.prototype.constructor === DaGe) // true
        console.log(instance.bart()); // 继承prototype返回type因为ErGe里有type所以为Er Ge
        console.log(instance.beat()); // 继承prototype返回type因为ErGe里没有beat()所以为Da Ge Hao
        console.log(instance.bart2()); // 报错因为此时指向DaGe并没有指向ErGe所以bart2并没有

相关文章

网友评论

      本文标题:Javascript 面向对象(ES5继承)

      本文链接:https://www.haomeiwen.com/subject/wjyfmctx.html