What is a class? In the program, the unified attribute structure and method definition of all sub-instances of a type are specially stored in a program structure. How to define class? The native definition of js:
function Student(name,age){
this.name= name ;
this.age = age;
}
Student.prototype.intr= function(){
console.log(`我叫${
this.name};我今年${
this.age}岁`)
}
var person = new Student('张三',18)
person.intr(); //我叫张三;我今年18岁
Use class definition:
- Wrap the original constructor + prototype object method with class{}
- The original constructor name is upgraded to the name of the entire class, and all constructors are renamed to constructor
- The method in the prototype object does not need to be prefixed with prototype or =function, and is directly abbreviated as: method name (){ ... ...}
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
intr() {
// 自动放入原型对象中
console.log(
`我叫${
this.name}, 我${
this.age}岁`);
}
}
var person = new Student('张三', 18)
person.intr(); //我叫张三;我今年18岁
Question: Where are the method definitions inside class{} stored? Result: They are all stored on the prototype object; their essence is the same, and the data structure that appears after printing person is the same.
Question: If the same attribute value is shared by multiple sub-objects, where should it be placed? How to access
Shared property placement: static className=“Senior One (2) Class”
Shared property access: Student.className
class{
constructor(name, age) {
this.name = name;
this.age = age;
}
static className="高一(2)班" // static 共有属性名=属性值
intr() {
// 自动放入原型对象中
console.log(
`我叫${
this.name}, 我${
this.age}岁`,${
Student.className});
}
}
}
The use of extends and super in class:
class people {
constructor(name, sex, age) {
this.name = name;
this.sex = sex;
this.age = age;
}
peopleAction() {
console.log(`我叫${
this.name},我是${
this.sex},我今年${
this.age}岁`)
}
}
class men extends people {
constructor(name, sex, age, noBirthBaby) {
super(name, sex, age)
this.noBirthBaby = noBirthBaby;
}
action() {
console.log(`我叫${
this.name},我是${
this.sex},我今年${
this.age}岁,我${
this.noBirthBaby}生娃`)
}
}
var tom = new men('Tom', '男', '5', '不会')
tom.peopleAction() //我叫Tom,我是男,我今年5岁 --使用父类的方法
tom.action() //我叫Tom,我是男,我今年5岁,我不会生娃
var Mill = new men('Mill', '女', '21', '会')
Mill.action() //我叫Mill,我是女,我今年21岁,我会生娃