1、面向对象

创建类:

  1. <script>
  2. /* class */
  3. function Person(name,age){
  4. this.name = name;
  5. this.age = age;
  6. }
  7. var cheng = new Person("lisi",19);
  8. console.log(cheng)
  9. </script>

image.png

2、ES6中构造函数

构造函数就是构造一个对象的函数
constructor(){
}

  1. <script>
  2. /* 构造函数就是构造一个对象的函数 */
  3. class Person{
  4. constructor(name,age){
  5. console.log("hello world")
  6. this.name = name;
  7. this.age = age;
  8. }
  9. }
  10. var li = new Person("lisi",18)
  11. </script>

image.png

3、extend继承

在继承的构造函数中super必须放在第一行
class Apple extends Computer{
constructor(name,price,skill){


super(name,price);
this.skill = skill;
}
}
子类会自动继承父类的方法

  1. <script>
  2. class Computer{
  3. constructor(name,price){
  4. this.name = name;
  5. this.price = price;
  6. }
  7. sayName(){
  8. console.log(this.name)
  9. }
  10. sayPrice(){
  11. console.log(this.price)
  12. }
  13. }
  14. class Apple extends Computer{
  15. constructor(name,price,skill){
  16. /* 在继承的构造函数中super必须放在第一行 */
  17. super(name,price);
  18. this.skill = skill;
  19. }
  20. }
  21. /* 子类会自动继承父类的方法 */
  22. var a = new Apple("苹果电脑",8888,"设计牛逼")
  23. console.log(a);
  24. a.sayName();
  25. a.sayPrice();
  26. </script>

image.png
1、class可以定义一个类
2、constructor 构造函数,new关键字实例化一个对象的时候调用
3、super指父类

  1. <script>
  2. /*
  3. 1、class可以定义一个类
  4. 2、constructor 构造函数,new关键字实例化一个对象的时候调用
  5. 3、super指父类
  6. */
  7. class Person{
  8. constructor(name,age){
  9. console.log("p")
  10. this.name = name;
  11. this.age = age;
  12. }
  13. sayName(){
  14. console.log(this.name);
  15. }
  16. }
  17. class Student extends Person{
  18. constructor(name,age,skill){
  19. console.log("s")
  20. super(name,age);
  21. this.skill = skill;
  22. }
  23. }
  24. var s = new Student("lisi",19,"wechat")
  25. s.sayName();
  26. </script>

image.png