es6学习笔记整理(十二)类和对象

类的概念

基本语法

类的基本定义和生成实例

class Parent{
    constructor(name='zhansan'){
        this.name = name;
    }
}
//生成实例
let v_parent = new Parent('lisi');//Parent {name: "lisi"}
console.log(v_parent);

类的继承
class Parent{
    constructor(name='zhansan'){
        this.name = name;
    }
}
//子类 继承extends
class Child extends Parent{

}

console.log(new Child());//Child {name: "zhansan"}

继承传参

            class Parent{
                constructor(name='zhansan'){
                    this.name = name;
                }
            }
            //子类 继承extends
            class Child extends Parent{
                constructor(name='child'){
                    super(name);//覆盖父级的属性,需要加上参数
                    //子类添加自己的属性,必须放在super()后面
                    this.type = 'child';
                }
            }

            console.log(new Child());//Child {name: "child", type: "child"}
静态方法

静态方法static:

  • 通过类调用,而不是通过类的实例去调用
 class Parent{
                constructor(name='zhansan'){
                    this.name = name;
                }

                static test(){
                    console.log('test');
                }
            }

            Parent.test();//test
静态属性
class Parent{
                constructor(name='zhansan'){
                    this.name = name;
                }

                static test(){
                    console.log('test');
                }
            }
            Parent.type = 'test1';

            console.log(Parent.type);//test1
getter\setter
            class Parent{
                constructor(name='zhansan'){
                    this.name = name;
                }
                //是属性,不是函数
                get firstName(){
                    return 'new:'+this.name;
                }
                set firstName(value){
                    this.name=value;
                }
            }

            var parent = new Parent();
            console.log(parent.firstName);//new:zhansan
            parent.firstName = 'lisi';
            console.log(parent.firstName);//new:lisi
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 领导必须比团队成员能够豁出去,能豁出去只是因为比别人更明白,没有别的选择
    吕明超阅读 748评论 0 0
  • /Home目录 lethomeDirectory=NSHomeDirectory() //Documents目录 ...
    762683ff5d3d阅读 7,046评论 0 0
  • 1. 标签定义外部的内容。2. 标签定义 article 以外的内容。3. 标签定义声音,比如音乐或其他音频流。 ...
    虎帅锅阅读 1,855评论 0 0
  • 悉心与照料,或许,是一种解药。 但,也或许,是一种毒药。 依赖会让自己忘记自己是一株植物, 习惯会让它依赖你给的所...
    戴恩米恩的月光阅读 2,118评论 0 2

友情链接更多精彩内容