js中的Class类详解_js class

但是为什么Person实例多出来的两个属性?

new 一个类发生了什么

类的静态属性和实例属性

类的私有属性

继承


什么是类?

class 类是一种抽象的体现,用来表示具有相同特性的一类事物,是面向对象编程(oop)不可缺少的工具。

定义一个简单的类

定义一个类为Person,每个Person都会跑,都有名字
class Person {
      constructor(surname, name) {
        this.surname = surname
        this.name = name
      }
      work() {
        console.log("我们会一直跑");
      }
      getName() {
        return this.surname + this.name
      }
    }
    const p1 = new Person("张", "三")
    p1.work()
    console.log(p1.getName());

毫无疑问执行代码肯定会打印 我们会一直跑 和 张三

看一下Person类 和 Person的实例

可以看到 Person实例的[[Prototype]]是指向Person的prototype的

但是为什么Person实例多出来的两个属性?

因为在new Person实例的时候,执行了constructor函数, 可以把它叫做构造器函数,这个构造器函数的this执行了实例, 所以给p1实例增加了俩个属性 name, surname,大家不用往上看了

constructor(surname, name) {
        this.surname = surname
        this.name = name
      }

其实上面的现象都是在new 一个类实例的结果,接下来看看new一个实例发生了什么

new 一个类发生了什么

  1. 在堆空间创建一个对象
  2. 对象的[[Prototype]]指向其构造函数的prototype的
  3. constructor 中this被赋值为这个对象
  4. 执行 constructor构造器函数 给对象创建属性
  5. 最后一点  如果constructor函数内返回了一个对象,则实例就是该对象,反之实例就是刚刚在堆内存中创建的对象

针对第五步的代码示例

    class Person {
      constructor(surname, name) {
        this.surname = surname
        this.name = name
        return { a: 1 }
      }
      work() {
        console.log("我们会一直跑");
      }
      getName() {
        return this.surname + this.name
      }
    }
    const p1 = new Person("张", "三")
    console.dir(Person);
    console.dir(p1);

类的静态属性和实例属性

实例属性是所有的实例都可以访问的属性,静态属性是只有类本身才能访问的, 静态属性通过static关键字来定义,或者直接Person.xxx

假设Person有一个秘密,只有他自己可以访问到

class Person {
      constructor(surname, name) {
        this.surname = surname
        this.name = name
        return { a: 1 }
      }
      work() {
        console.log("我们会一直跑");
      }
      getName() {
        return this.surname + this.name
      }
      static secret() {
        return "我的秘密是 xxxxxx"


### 最后



跑");
      }
      getName() {
        return this.surname + this.name
      }
      static secret() {
        return "我的秘密是 xxxxxx"


### 最后



>![](https://img-blog.csdnimg.cn/img_convert/fad52582284390fb464a99886ab8754c.webp?x-oss-process=image/format,png)
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值