一.构造函数和原型对象
1.构造函数:
(1)作用:用于创建对象,初始化对象的属性
在ES5中创建构造函数:
function Student(id,name){
this.id = id
this.name = name
}
在ES6中创建类,给类单独定义构造函数
class Student{
constructor(id,name){
this.id = id
this.name = name
}
}
let s1 = new Student(1001,'西西')//自动调用constructor函数
注意:通常把用构造函数创建对象的过程称为类的实例化,对象就是类的实例
2.构造函数的成员或类的成员
(1)什么是成员?类的成员包括属性、方法(行为),通常将属性称为成员变量,把方法(行为)称为成员方法(成员函数)
(2)成员变量又称为实例变量:用类或构造函数创建的对象都具有相同的属性和方法
class Person{
constructor(id,name){
this.id = id
this.name = name
}
display(){
console.log('编号:',this.id)
console.log('姓名:',this.name)
}
}
let person1 = new Person(101,'西西')
person1.display()
let person2 = new Person(102,'懒羊羊')
person2.display()
console.log(person1 == person2)//false
//对象person1和person2的属性和方法是相同的,但它们在内存中的存储空间是不同的
(3)静态成员:通过构造函数名或类名直接访问的成员。不属于任何对象,为类的所有对象(实例共享的)
静态成员也称为类成员
ES6中的静态成员
class Student{
constructor(stuId,stuName){
Student.schoolName = '西工大'//schoolName是静态成员,通过类名直接访问:类成员为类的所有对象共享
this.stuId = stuId//stuId是实例成员,属于具体的实例(对象)
this.stuName = stuName//stuName是实例成员,属于具体的实例(对象)
}
display(){
console.log('school:',Student.schoolName)
console.log('id:',this.stuId)
console.log('name:',this.stuName)
}
}
let student1 = new Student(101,'懒羊羊')
let student2 = new Student(102,'暖羊羊')
let student3 = new Student(103,'