1.原型链

JavaScript规定,所有对象都有自己的原型对象(prototype)。一方面,任何一个对象,都可以充当其他对象的原型

  1. <script>
  2. /* 为什么一个实例化的对象能够使用它原型上的方法 */
  3. function Person(name,age){
  4. this.name = name;
  5. this.age = age;
  6. }
  7. Person.prototype.sayName = function(){
  8. console.log(this.name)
  9. }
  10. /*
  11. 1.每个对象都有一个隐藏属性__proto__,它指向它的原型对象
  12. 2.这个对象会享有原型上的属性或者方法
  13. */
  14. var wang = new Person("wangyuhuan",18)
  15. console.log(wang)
  16. // wang.sayName = function(){
  17. // console.log("wang")
  18. // }
  19. // wang.sayName()
  20. console.log(wang.__proto__) //里面有sayname()
  21. console.log(wang.__proto__==Person.prototype) //true
  22. </script>

原型链.png

2.继承

  1. <script>
  2. // function Person(name,age){
  3. // this.name = name;
  4. // this.age = age;
  5. // }
  6. // Person.prototype.sayName = function(){
  7. // this.name;
  8. // }
  9. class Person{
  10. constructor(name,age){
  11. this.name= name;
  12. this.age = age
  13. }
  14. sayName(){
  15. console.log(this.name)
  16. }
  17. }
  18. /* 使用extends关键可以实现继承,之后自动拥有父类的属性和方法 */
  19. class Student extends Person{
  20. constructor(name,age,skill){
  21. super(name,age);
  22. this.skill = skill
  23. }
  24. saySkill(){
  25. console.log(this.skill)
  26. }
  27. }
  28. var cheng = new Person("chengchao",18);
  29. /* 父类不能使用子类的方法 */
  30. cheng.saySkill()
  31. var s = new Student("lisi",17,'js')
  32. // s.sayName()
  33. console.log(s.__proto__) //Person
  34. </script>
  1. <script>
  2. /*
  3. 1. class实现一个类
  4. 2. constructor关键字实现构造函数
  5. 3.类中的方法是写在原型上的
  6. 4.extends关键字能够实现继承
  7. 5.在子类的方法中去调用父类的方法使用this就可以调用
  8. */
  9. /*
  10. 1.es5构造函数--实现了类
  11. 2.new关键字实例化了对象
  12. 3.原型
  13. 4.原型链
  14. */
  15. class Person{ //Person类
  16. constructor(name,age){
  17. this.name= name;
  18. this.age = age
  19. } //构造函数
  20. sayName(){
  21. console.log(this.name) //构造函数方法
  22. } //写在原型对象上
  23. }
  24. /* 在子类的方法中去调用父类的方法 */
  25. class Student extends Person{
  26. constructor(name,age,skill){
  27. super(name,age);
  28. this.skill = skill
  29. }
  30. saySkill(){
  31. this.sayName()
  32. }
  33. }
  34. var cheng = new Student("lisi",12,'js');
  35. cheng.saySkill()
  36. var p = new Person("zhangsan",18)
  37. console.log(Person.prototype) //有sayName
  38. </script>

Object.png