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);


手掌心
浏览 993回答 1
1回答

繁花如伊

用ES6简化了下:    class Person {     }    class Friend extends Person {     }          console.log('%O', Person.prototype.constructor); // Person     console.log('%O', Friend.prototype.constructor); // FriendES6中已经修复了这个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类时返回的对象中的constructor是Person本身,但是在后续实例化等过程中不会直接使用到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(); // helloconsole.log(f);通过上面的例子可以看出修正了的constructor与没有修改的差别是扩展的sayHello方法在原型链上加的位置不一样了。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript