javascript - js组合继承中斧正constructor的指向有什么用。

查看:129
本文介绍了javascript - js组合继承中斧正constructor的指向有什么用。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

Friend.prototype.constructor = Friend
原先Friend.prototype.constructor指向的是Person
但是感觉并没有什么用

有没有弹出的结果都一样,感觉都很好完成了继承

function Person(name,age){
            this.name = name;
            this.age = age;
            if(typeof this.sayName != 'function'){
                Person.prototype.sayName = function(){
                    alert(this.name);
                }
            }
        }
        
        var per1 = new Person('zhang',23);
        var per2 = new Person('wagn',23);

        
        function Friend(name,age,sex){
            Person.call(this,name,age);
            this.sex = sex;
        } 
            Friend.prototype = new Person();
            Friend.prototype.constructor = Friend; //不斧正时,constructor指向Person
            Friend.prototype.saySex=function(){
                alert(this.sex);
            }
        
        var fri1 = new Friend('wang','11','nan');
        var fri2 = new Friend('li','55','nv');

        alert(Person.prototype.constructor);

解决方案

ES6class语法理解应该会好一点,手机回复,可以先参考mdn,如果不能理解,稍后补全。


更新:
看完其它评论才发现自己理解基础知识也是有时没有太深入,导致一时也不能很好的回复这个问题,但是既然回复了,还是好好的编辑一下自己理解的答案。
用ES6简化了下:

    class Person {

    }

    class Friend extends Person {

    }
    
    console.log('%O', Person.prototype.constructor); // Person
    console.log('%O', Friend.prototype.constructor); // Friend

ES6中已经修复了这个constructor,始终指向类本身
用ES5简化下:

    function Person() {
    
    }
    
    function Friend() {
    
    }
    
    Friend.prototype = new Person();
    // Friend.prototype.constructor = Friend;
    console.log('%O', Person.prototype.constructor); // Person
    console.log('%O', Friend.prototype.constructor); // Person

为什么Friend.prototype.constructor也是Person,这里题主是知道的。我还是自己学习再次总结下,因为实例化Person类时返回的对象中的constructorPerson本身,但是在后续实例化等过程中不会直接使用到constructor,但是出于对该函数本身的含义的理解,于是我们修正了constructor

constructor 的含义是 返回指向创建了该对象原型的函数引用


相关应用例子:

var f = (function() {
    function Person() {
    
    }
    
    function Friend() {
    
    }
    
    Friend.prototype = new Person();
    // Friend.prototype.constructor = Friend;
    return new Friend();
}())
// 如果需要扩展原型方法
f.constructor.prototype.sayHello = function() {
    console.log('hello');
}
f.sayHello(); // hello
console.log(f);

通过上面的例子可以看出修正了的constructor与没有修改的差别是扩展的sayHello方法在原型链上加的位置不一样了。

这篇关于javascript - js组合继承中斧正constructor的指向有什么用。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆