创建类和对象

本文介绍了JavaScript中的类创建和继承概念。通过`class`关键字定义类,并展示了`constructor`构造函数的使用,用于初始化对象属性。此外,还讨论了如何在类中添加方法,例如`sing`方法。最后,通过`extends`关键字演示了类的继承,并调用父类的构造函数`super`。示例中创建了两个Person类的实例并输出,以及Son类从Father类继承并调用`sum`方法的示例。

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

  1. 通过class 关键字创建类, 类名我们还是习惯性定义首字母大写
  2. 类里面有个constructor 函数,可以接受传递过来的参数,同时返回实例对象  
  3. constructor 函数 只要 new 生成实例时,就会自动调用这个函数, 如果我们不写这个函数,类也会自动生成这个函数      
  4. 生成实例 new 不能省略   
  5. 最后注意语法规范, 创建类 类名后面不要加小括号,生成实例 类名后面加小括号, 构造函数不需要加function
         class Person {
           constructor(theName, theSex) {
             this.name = theName;
             this.sex = theSex;
           }
         }
         var per1 = new Person("老黄", 18);
         var per2 = new Person("老刘", 15);
         console.log(per1);
         console.log(per2);

6.在类中添加方法

         class Person {
           constructor(theName, theSex) {
             this.name = theName;
             this.sex = theSex;
           }
             sing(song){
                console.log(this.uname + song);
             }
         }
         var per1 = new Person("老黄", 18);
         var per2 = new Person("老刘", 15);
         console.log(per1);
         console.log(per2);
         per1.sing('在吃饭')
         per2.sing('在工作')    

7.继承类

     class Father {
            constructor(x, y) {
                this.x = x;
                this.y = y;
            }
            sum() {
                console.log(this.x + this.y);
            }
        }
        class Son extends Father {
            constructor(x, y) {
                super(x, y); //调用了父类中的构造函数
            }
        }
        var son = new Son(11, 22);
        var son1 = new Son(1, 2);
        son.sum();
        son1.sum();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值