0
点赞
收藏
分享

微信扫一扫

【JavaScript】ES6 中class定义类

程序小小黑 2022-07-12 阅读 74

在这里插入图片描述

文章目录

🍋前言

🍉正文

1.声明类的两种方式:

  • class 关键字 类的声明
class Person{}
  • 类表达式(不常用)
var People = class { }
console.log(Person.prototype) // Person {}
console.log(Person.prototype.__proto__) // {}
console.log(Person.constructor) // [Function: Function]
console.log(typeof Person) // function

2.class 类的构造函数

如果我们希望在创建对象的时候给类传递一些参数,这个时候应该怎么做呢?

  • 每个类都可以有一个自己的构造函数(方法),这个方法的名称是固定的 constructor
  • 当我们通过new操作符,操作一个类的时候会调用这个类的构造函数constructor
  • 每个类只能有一个构造函数,如果包含多个构造函数,那么会抛出异常。

示例代码如下:

// 类的声明
class Person {
    // 类的构造方法
    constructor(name, age) {
        this.name = name
        this.age = age
    }
    foo () {
        console.log(this.name)
    }
}
var p1 = new Person('h', 19)

console.log(p1)// Person { name: 'h', age: 19 }
p1.foo() // h

3.class中方法定义

3.1 class 中定义普通的实例方法

class Person {
    // 类的构造方法
    constructor(name, age) {
        this.name = name
        this.age = age
        this._address = '北京市'
    }
    eating () {
        console.log(this.name + ' 正在eating~')
    }
    running () {
        console.log(this.name + ' 正在running~')
    }
}

var p1 = new Person('jam', 19)
console.log(p1)
p1.eating()
p1.running()

3.2 class 类中定义访问器方法

class Person {
    // 类的构造方法
    constructor(name, age) {
        this.name = name
        this.age = age
        this._address = '北京市'
    }
    // 类的访问器方法
    get address () {
        // 在这里可以设置拦截访问操作
        console.log('获取呢')
        return this._address
    }
    set address (newValue) {
        // 在这里可以设置拦截设置操作
        console.log('修改呢')
        return this._address = newValue
    }
}

var p1 = new Person('jam', 19)
console.log(p1.address)
p1.address = '天津市'
console.log(p1.address)

3.3 类的静态方法(类方法)

小案例:使用类的静态方法完成随机生成Person实例

class Person {
    // 类的构造方法
    constructor(name, age) {
        this.name = name
        this.age = age
        this._address = '北京市'
    }
    
    // 类的静态方法(也称为类方法)  创建对象随机生成一个名字小案例
    static randomPerson () {
        // 创建一个存储名字的数组
        let names = ['jam', 'jak', 'jag', 'jao', 'jno']
        // Math.random()生成一个0-1之间的数字,小数肯定是不对的
        let nameIndex = Math.floor(Math.random() * names.length)
        let name = names[nameIndex]
        // 生成随机年龄
        let age = Math.floor(Math.random() * 100)
        // return随机生成的人物 姓名+ 年龄
        return new Person(name, age)
    }
}
  • 随机生成一个Person实例(附效果图)
// 随机生成一个  
var p2 = Person.randomPerson()
console.log(p2)

请添加图片描述

  • 随机生成多个Person实例(附带效果图)
// 随机生成多个
for (let index = 0; index < 20; index++) {
    console.log(Person.randomPerson())
}

请添加图片描述

🥭文末

举报

相关推荐

0 条评论