js原型继承 - 草稿

js原型继承--使用构造函数和空函数修复原型链解决的问题

//父类构造函数
            function People(props){
                this.name = props.name;
                this.speak = function (){
                    alert(this.name + ' is speaking');
                }
            }
//子类构造函数
            function Teacher(props){
                People.call(this,props);
                this.teach = function(){
                    alert(this.name+' is teaching');
                }
                this.speak = function (){
                    alert('when '+this.name+'is speaking, he is teaching')
                }
            }
//空函数用来修复原型链
            function Adapter(){}
            Adapter.prototype = People.prototype;
            Teacher.prototype = new Adapter();
//修复constructor
            Teacher.prototype.constructor = Teacher;
            People.prototype.gender = 'male';
            //Teacher.prototype.gender = 'female';
            var teacher = new Teacher({name:'jack'});
            var people = new People({name:'jim'});
            teacher.speak();
            teacher.teach();
            alert(people.gender);
            alert(teacher.gender);//如果不修复原型链则teacher的原型链关系:__proto__-->Teacher.prototype-->Object.prototype-->null
//则People.prototype扩展属性的时候无法继承到
//如果直接Teacher.prototype=People.prototype, 则会引用同一个prototype, 给Teacher.prototype扩展属性的时候会影响到People的实例对象

总结就是:

  1. 每个对象都有一个proto属性
  2. 每个函数都有一个prototype属性
  3. 定义一个函数隐含的有
  4. js访问一个对象的属性或方法的时候会首先在这个对象里面寻找,如果找不到则去原型链指针prototype指向的对象去找,如果找不到会一直沿着prototype找下去
  5. 一个对象的prototype正常应该指向继承对象

你可能感兴趣的:(js原型继承 - 草稿)