JavaScript——class与原型对象

原型对象的意义

  • 通过new 一个构造函数,我们能够获得一个实例,在new 的过程中,程序会在内存中申请一块区域,同时我们可以加参数,所以每个对象都不一样。
  • 原型对象则是同一个构造函数 new 出来的所有实例同时拥有一个原型对象,原型对象上挂在的属性或者方法是固定的提供这些实例使用
  • 以上得出,原型对象的优点,固定为所有实例提供属性或方法,不会额外加内存
  • 应用场景,每个对象独有的属性用构造函数,共有的属性和方法挂载到原型对象上

class

实例属性,写入在constructor中

静态属性与方法,写在constructor外,用static修饰

原型对象,写在constructor外

<script>
    class Person {
        constructor(name, age) {
            this.name = name;
            this.age = age
        }
     // 挂载到原型对象上
        Say() {
            console.log('I am  human')
        }
    }
    console.log(new Person('ss', 14))
</script>

继承,子类继承使用extends关键字,当子类需要写入私有的属性,必须添加constructor以及super(),super() 相当于父类构造器的引用,this关键字必须在super之后

<script>
    class Person {
        constructor(name, age) {
            this.name = name;
            this.age = age
        }

        // 挂在到原型对象上
        Say() {
            console.log('I am  human')
        }
    }
    class Student extends Person {
        constructor(name, age, id) {
            super(name, age)
            this.id = id
        }
    }
    console.log(new Student('ww', 14, 14))
</script>

猜你喜欢

转载自www.cnblogs.com/wuqiuxue/p/9240292.html