1,继承 Prototype:
- Student.prototype = Person.prototype; //执行完此句时,Student.prototype.constructor 指向的是Person,为什么了?因为Person.prototype.constructor指向Person,对象的赋值实质上是引用赋值,所以Student.prototype.constructor也指向Person
- Student.prototype.constructor = Student; // 将Student.prototype.constructor 指回Person
用 Person 的原型对象来覆盖 Student 的原型对象;前面说到对象的赋值实质上是引用赋值,所以如果 Student.prototype 上的任何修改都会体现到 Person.prototype 中,即子类会影响父类。
看下面:
- Student.prototype.add = function() {
- alert("add")
- };
- Person.prototype.add(); //弹出add
2,继承实例:
- Student.prototype = new Person(); //如果此处不传递参数,可以不写();即直接写成 new Person;
- 2 Student.prototype.constructor = Student;
用 Person 的实例来覆盖 Student 的原型对象;创建了实例,比起前面那种,显示是浪费内存了,不过这同时也解决了上面那种方法的缺点,即此时 Student.prototype 上的任何修改不会体现到 Person.prototype 中,即子类不会影响父类。
3,利用控对象来组合 1 和 2 的优点,去掉缺点
- var F = function(){};
- F.prototype = Person.prototype;
- Student.prototype = new F();
- Student.prototype.constructor = Student;
F 是个空对象,上面只有些原型方法,实例化时内存占用较少,同时也隔离开了子类对父类的影响。
来源: