1. 1 class 可以定义一个类
  2. 2 constructor 构造函数
  3. 3 new关键字实例化一个对象
  4. 4 super指父类
  1. <script>
  2. class Compute{
  3. constructor(name,price){
  4. //constructor 里面的this指向的是 创建的实例对象
  5. this.name = name;
  6. this.price = price;
  7. }+
  8. sayName(){
  9. console.log(this.name);
  10. }
  11. }
  12. class Apple extends Compute{
  13. constructor(name,price,skill){
  14. // 在继承的构造函数中super必须放在第一行
  15. // super 可以继承父类中的方法和属性
  16. super(name,price); //调用父类构造函数
  17. this.skill = skill
  18. }
  19. }
  20. var a = new Apple("苹果",8888,"exllence");
  21. console.log(a);//Apple {name: '苹果', price: 8888, skill: 'exllence'}
  22. a.sayName() //苹果
  23. </script>

1-1 class定义一个简单的类

  1. class Person{
  2. constructor(name,age){
  3. this.name = name;
  4. this.age = age
  5. }
  6. }

直接定义在class中的属性,还是实例私有的属性。

  1. class Person{
  2. skill = "javascript"
  3. constructor(name,age){
  4. this.name = name;
  5. this.age = age
  6. }
  7. }
  8. console.log(p.hasOwnProperty("skill"))

1-2 共有方法

  1. class Person {
  2. constructor(name, age) {
  3. this.name = name;
  4. this.age = age
  5. }
  6. sayName(){
  7. console.log(this.name)
  8. }
  9. }
  10. var p = new Person("cheng", 18);
  11. p.sayName()

1-3 添加共有的方法

Object.assign()

es6不支持使用直接量的方式在原型上添加

     class Person {
            constructor(name, age) {
                this.name = name;
                this.age = age
            }
            sayName() {
                console.log(this.name)
            }
        }

        Person.prototype = {
            sayAge() {
                console.log(this.age)
            }
        } 
# 会报错
            class Person {
            constructor(name, age) {
                this.name = name;
                this.age = age
            }
            sayName() {
                console.log(this.name)
            }
        }

        Object.assign(Person.prototype,{
            sayAge(){
                console.log(this.name)
            },
            saySkill(){
                console.log("前端")
            }
        })
        var p = new Person("cheng",16);
        p.sayAge()

1-4 继承

class Person{
  constructor(name,age){
    this.name = name;
    this.age = age
  }
  sayName(){
    console.log(this.name);
  }
}
class Teacher extends Person{
  // 类继承之后,构造函数第一行必须写super关键字,去继承父类的属性
  constructor(name,age,skill){
    super(name,age)
    this.skill = skill 
  }
  // 在子类的方法中调用父类的方法 (this或super去调用)
  show(){
    super.sayName()
    // this.sayName()
  }
}
var t = new Teacher("zhang",18,"js")
console.log(t);
t.sayName()