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

本文介绍JavaScript中类的基本概念与使用方法,包括类的定义、实例化、继承及静态方法等特性,并展示了如何利用getter和setter进行属性操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

类的概念
基本语法

类的基本定义和生成实例

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值