1-1 call实现属性继承

  1. function Person(name,age){
  2. this.name = name;
  3. this.age = age;
  4. }
  5. function Teacher(name,age,skill){
  6. var self = this;
  7. Person.call(self,name,age)
  8. this.skill = skill;
  9. }
  10. var t = new Teacher("zhang",18,"js");
  11. console.log(t)
  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)
  7. this.skill = skill;
  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 Student(name,age,skill){
  9. Person.call(this,name,age);
  10. this.skill=skill;
  11. }
  12. Student.prototype = new Person();
  13. Student.prototype.constructor = Student;
  14. var s = new Student("cheng",18,"js");
  15. console.log(s.constructor == Student)
  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 Student(name,age,skill){
  9. Person.call(this,name,age);
  10. this.skill=skill;
  11. }
  12. Student.prototype = Person.prototype;
  13. Student.prototype.constructor = Student;
  14. Student.prototype.sayAge = function(){
  15. console.log(this.age)
  16. }
  17. var s = new Student("cheng",18,"js");
  18. console.log(s.constructor == Student)

1-3 Object.create实现继承

如果想创建一个继承自其他对象的对象,可以使用Object.create()指定[[Prototype]]为一个新的对象。

  1. function Person(){
  2. }
  3. Person.prototype.sayName = function(){
  4. console.log("name")
  5. }
  6. function Teacher(){
  7. }
  8. Teacher.prototype = Object.create(Person.prototype,{
  9. constructor:{
  10. value:Teacher
  11. }
  12. });
  13. var t = new Teacher();
  14. var p = new Person();
  15. console.log(t);