es5利用改变this指向继承

利用构造函数继承父类属性(es5)

1.在构造函数中,this指向实例对象;

2.原型对象prototype中,this指向实例对象;

function Father(uname, age) {
            this.uname = uname;
            this.age = age
        }
        Father.prototype.money = function() {
            console.log(100000);

        }

        function Son(uname, age, score) {
      //此时,利用call()改变了Father的this指向,使其指向子构造函数,以达到调用父类的属性 Father.call(
this, uname, age) this.score = score; } Son.prototype = new Father(); //利用实例对象修改了原型对象,需要利用constructor指会原来的构造函数;
    Son.prototype.constructor = Son;
     var son = new Son('张三', 16, 80);
    console.log(son);
     son.money();
注意:不能使用Son.prototype = Father.prototype,因为这样修改了子原型对象,父类也会跟着变化,
使用Son.prototype = new Father()使得子原型对象指向了父类的实例对象,而父类的实例对象中有__proto__,它会指向父类的原型对象,可以拿到其中的方法;(如下图所示)


 

posted @ 2020-07-13 22:29  流弊的小涛  阅读(180)  评论(0编辑  收藏  举报