js中的Class类详解_js class(1)

定义一个类为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"
      }
    }
    const p1 = new Person("张", "三")
    console.log(Person.secret());
    try {
      p1.secret()
    } catch (error) {
      console.log(error);
    }
    console.dir(Person);

细心的同学可能已经发现了,通过static关键字设置的静态属性直接挂在Person类对象上了,实例属性都是挂在prototype上的,这更加验证了new关键字的五个步骤

类的私有属性

我们可以为每一个类实例都定义私有属性,在生活中每个人都有个人隐私,比如说女生不愿意透露的身高体重等等,在类中也可以实现类似的

  class Person {
      #height
      constructor(surname, name) {
        this.surname = surname
        this.name = name
        this.#height = "120cm"
      }
      work() {


### 最后

我可以将最近整理的前端面试题分享出来,其中包含**HTML、CSS、JavaScript、服务端与网络、Vue、浏览器、数据结构与算法**等等,还在持续整理更新中,希望大家都能找到心仪的工作。


**篇幅有限,仅展示部分截图:**

![](https://img-blog.csdnimg.cn/img_convert/ff6b8e636a356a01389cd2de0211d347.png)

![](https://img-blog.csdnimg.cn/img_convert/b24f32dd81ead796fa80c27c763d262c.png)

![](https://img-blog.csdnimg.cn/img_convert/c6265dc2681708533916a8d7910506b3.png)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值