原型对象:Javascript的继承是基于原型的继承

1.属性继承:call

  1. <script>
  2. // 定义两个类,Person Teacher
  3. function Person(name,age){
  4. this.name = name;
  5. this.age = age;
  6. }
  7. function Teacher(name,age,skill){
  8. var self = this;
  9. Person.call(self,name,age);//直接调用Person继承属性,call改变Person内部this指向
  10. this.skill = skill;
  11. }
  12. var t = new Teacher("zhang",18,"js");
  13. console.log(t)
  14. //输出Teacher{name:"zhang",age:18,skill:"js"}
  15. </script>

2.方法继承

Teacher.prototype = Person.prototype;
重置构造属性:Teacher.prototype.constructor = Teacher;

  1. <script>
  2. /* Person Teacher */
  3. /*
  4. 原型对象:Javascript的继承是基于原型的继承
  5. call能够实现属性的继承
  6. */
  7. function Person(name,age){
  8. this.name = name;
  9. this.age = age;
  10. }
  11. Person.prototype.sayName = function(){
  12. console.log(this.name)
  13. }
  14. function Teacher(name,age,skill){
  15. Person.call(this,name,age)
  16. this.skill = skill;
  17. }
  18. Teacher.prototype.sayAge = function(){
  19. console.log(this.age)
  20. }
  21. /* 方法的继承 */
  22. Teacher.prototype = Person.prototype;
  23. Teacher.prototype.constructor = Teacher;//重置构造属性
  24. var t = new Teacher("zhang",18,"js");
  25. var p = new Person("lisi",13);
  26. console.log(t.constructor)
  27. </script>