目录

什么是类?

定义一个简单的类

定义一个类为Person,每个Person都会跑,都有名字

看一下Person类 和 Person的实例 

但是为什么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 一个类发生了什么

在堆空间创建一个对象对象的[[Prototype]]指向其构造函数的prototype的constructor 中this被赋值为这个对象执行 constructor构造器函数 给对象创建属性最后一点  如果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() {

console.log("我们会一直跑");

}

getName() {

return this.surname + this.name

}

secret() {

console.log(this.#height);

return "我的秘密是 xxxxxx"

}

}

const p1 = new Person("张", "三")

console.dir(p1);

p1.secret()

类的私有属性只能在当前类中访问,对照上面的代码就是只能在secret中访问,类之外的地方访问就会报以下的错

继承

继承是面对对象编程的三大特性之一,js中通过extends来实现继承,需要注意的是字类继承父类时需要调用super函数,作用就是调用父类的constructor,还要注意不要再super前访问this

class Father {

constructor(money) {

this.money = 1000000

}

}

class Son extends Father {

constructor() {

super()

}

}

const S1 = new Son()

console.dir(S1);

暂时就先说这么多,后续有发现再补充

查看原文