原型继承

JavaScript的原型继承实现方式就是:

  1. 定义新的构造函数,并在内部用call()调用希望“继承”的构造函数,并绑定this;

  2. 借助中间函数F实现原型链继承,最好通过封装的inherits函数完成;

  3. 继续在新的构造函数的原型上定义新方法。

  我们让teacher继承student

  function student(name) {     
            this.name = name || "ss";
        }
 
        function teacher(props) {
            student.call(this, props);      //关键
            this.techername="lll";
        }
        function f() {    //空函数用于桥接
        }
        f.prototype = student.prototype;
        teacher.prototype = new f();
        teacher.prototype.constructor=teacher; //将teacher的原型构造函数指向自己
 
        teacher.prototype.showname = function () {
            console.log(this.name,this.techername)
        }
 
        var xiaoming = new teacher("小明");
        xiaoming.showname(); //小明
        console.log(xiaoming.__proto__);//student
        console.log(xiaoming.__proto__.constructor);//f teacher
 
*封装
function inherits(Child, Parent) {
    var F = function () {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}

 

posted @ 2019-11-05 23:27  淡薄幽清  阅读(34)  评论(0)    收藏  举报