ES6语法(11)

来源:互联网 发布:js then方法 编辑:程序博客网 时间:2024/05/29 06:54

ES6中的类


一、定义类的基本方法

        {
            class Parent{
                
            }
        }

此时定义了一个空的类,没有具体内容。


constructor是构造函数,实例化还是用new。

        {
            class Parent{
                constructor(name="jack"){
                    this.name = name;
                }
            }
            
            let newParent = new Parent("pull");
            console.log(newParent);
        }



二、继承 extends

        {
            class Parent{
                constructor(name="jack"){
                    this.name = name;
                }
            }
            
            class Child extends Parent{
            
            }
            
            console.log(new Child);    //继承了Parent中的name
        }



继承传递参数

        {
            class Parent{
                constructor(name="parent"){
                    this.name = name;
                }
            }
            
            class Child extends Parent{
                constructor(name="child"){
                    super(name);        //用自己的参数
                    this.type="child";   //this必须写在super后面
                }
            }
            
            console.log(new Child);
        }


三、类中的getter  setter

        {
            class Parent{
                constructor(name="parent"){
                    this.name = name;
                }
                
                get longName(){
                    return "longName" + this.name;
                }
                
                set longName(value){
                    this.name = value;
                }
            }
            
            let newParent = new Parent(); 
            console.log(newParent.longName);  //longNameparent
            newParent.longName = "jack";    //重新设置了name
            console.log(newParent.longName);   //longNamejack
        }


四、静态方法

从类调用,不是从类的实例调用。

        {
            class Parent{
                constructor(name="parent"){
                    this.name = name;
                }
                
                static tell(){
                    console.log("tell");
                }
            }
            
            Parent.tell();   //tell
        }


五、静态属性

        {
            class Parent{
                constructor(name="parent"){
                    this.name = name;
                }

            }
            
            let newP = new Parent();
            newP.prop = 1;
            
            console.log(newP.prop);   //1
        }

原创粉丝点击