• 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>

  • 相关阅读:
    android中的webview白屏问题
    7-24分享
    Excel----考勤表制作自动更新日期
    (二十五)微信小程序的登陆 实际逻辑
    微信退款流程
    (二十八)加锁
    (二十七)竞价
    (二十六)拍卖专场相关的接口
    (二十六)微信小程序支付流程
    (二十四)微信小程序支付
  • 原文地址:https://www.cnblogs.com/wuqiuxue/p/9240292.html
Copyright © 2020-2023  润新知