1、构造函数:
作用:用于创建对象,初始化对象的属性
- //在ES5中创建函数:
- function Student(id,name) {
- this.id = id
- this.name = name
- }
- let s1 new = new Student {
- construction (id,name) {
- this.id = id
- this.name = name
- }
- }
- let s1 new Student (101,'张二')//自定调用construction函数
注意:通常吧构造函数创建对象的过程称为类的实例化,对象就是类的示例
2、构造函数的成员或类的成员
(1)什么是成员?类的成员包括属性、方法(行为),通常将属性称为成员变量,把方法(行为)称为成员方法(成员函数)
(2)成员变量又称为实例变量:用类或构造函数创建的对象都有相同的属性和方法
- class Person {
- constructor (id,name) {
- this.id = id
- this.name = name
- }
- display () {
- console.log("编号:",this.id)
- console.log("姓名:",this.name)
- }
- }
-
- let p1 = new Person('101','张三')
- let p2 = new Person('102','李四')
-
- //对象p1和p2的属性和方法是相同的,但它们在内存中的存储空间是不同的
(3)静态成员:通过构造函数名和类名直接访问的成员,不属于任何对象,为类的所有对象(实例共享的)
静态成员也成为类成员
- //ES6中的类额静态成员
- class Student{
- constructor( studentId, studentName){
- Student. schoolName = '西北工业大学' //schoolName是静态成员,通过类名直接访问:类成员为类的的所有对象共享
- this. studentId = studentId //studentId是实例成员,属于具体的实例(对象)
- this. studentName = studentName //studentName是实例成员,属于具体的实例(对象)
- }
- display(){
- console.log("学校: ", Student. schoolName )
- console.log("学号: ", this. studentId )
- console.log