js组合继承中斧正constructor的指向有什么用。
高洛峰
高洛峰 2016-11-10 09:22:57
0
3
785

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


高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all (3)
三叔

关于constructor的修正,我想关乎到其后续使用吧,同时我觉得这也保证了面向对象的合理性吧,保持constructor指向自家构造器的特征

    学霸

    绝大多数情况是不用修正的,但是如果在不修正的情况下你这么写 new Friend.prototype.constructor()返回的并不是一个Friend对象而只是Person对象。

      三叔

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

        Latest Downloads
        More>
        Web Effects
        Website Source Code
        Website Materials
        Front End Template
        About us Disclaimer Sitemap
        php.cn:Public welfare online PHP training,Help PHP learners grow quickly!