Javascript的继承是基于原型的继承

1-1 属性的继承

  1. # call 实现属性的继承
  1. function Person(name,age){
  2. this.name = name;
  3. this.age = age
  4. }
  5. function Teacher(name,age,skill){
  6. Person.call(this,name,age) // Person(name,age)中的this指向window,需要改变this指向
  7. this.skill = skill // this指向 Teacher构造函数的实例对象
  8. }
  9. var t = new Teacher("zhang",18,"js")
  10. console.log(t);

1-2 方法的继承

  1. function Person(name,age){
  2. this.name = name;
  3. this.age = age
  4. }
  5. Person.prototype.sayName = function(){
  6. console.log(this.name);
  7. }
  8. function Teacher(name,age,skill){
  9. Person.call(this,name,age)
  10. this.skill = skill
  11. }
  12. +Teacher.prototype = Person.prototype;
  13. +Teacher.prototype.constructor = Teacher;
  14. Teacher.prototype.sayAge = function(){
  15. console.log(this.age);
  16. }
  17. var t = new Teacher("zhang",18,"js")
  18. console.log(t);
  19. +t.sayName()
  20. t.sayAge()

1-2-1 es5中实现继承的方法

  1. function Person(name,age){
  2. this.name = name;
  3. this.age = age
  4. }
  5. Person.prototype.sayName = function(){
  6. console.log(this.name);
  7. }
  8. function Teacher(name,age,skill){
  9. Person.call(this,name,age)
  10. this.skill = skill
  11. }
  12. Teacher.prototype = Object.create(Person.prototype,{
  13. constructor:{
  14. value:Teacher
  15. }
  16. })
  17. Teacher.prototype.sayAge = function(){
  18. console.log(this.age);
  19. }
  20. var t = new Teacher("zhang",18,"js")
  21. console.log(t);
  22. console.log(t.constructor);
  23. t.sayName()
  24. t.sayAge()