为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

手掌心 2018-09-06 09:11:49
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);
查看完整描述

1 回答

?
繁花如伊

TA贡献2012条经验 获得超12个赞

用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(); // helloconsole.log(f);

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


查看完整回答
反对 回复 2018-10-27
  • 1 回答
  • 0 关注
  • 992 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信