1-1 类
类:就是具有一类相同特征的事物的抽象。对象:某类事物具体的实例。
/*function Person(name,age){ this.name = name this.age = age}Person.prototype = { constructor:Person, sayName(){ console.log(this.name); }}*/class Person{ constructor(name,age){ // constructor 函数--构造一个对象的函数 this.name = name; this.age = age } sayName(){ console.log(this.name); }}Person.prototype.sayAge = function(){ console.log(this.age);}// 不允许以字面量的形式去添加属性的/* Person.prototype = { sayAge(){ console.log(this.age); }} */var p = new Person("cheng",19)console.log(p);p.sayAge() // 19
1-2 Object.assign
可以在原型上添加多个属性
class Person{ constructor(name,age){ this.name = name; this.age = age; } sayName(){ console.log(this.name); }}Object.assign(Person.prototype,{ sayAge(){ console.log(this.age); }, show(){ console.log("show"); }})var p = new Person("cheng",18)console.log(p.constructor == Person); // truep.sayAge() // 18console.log(p);
1-3 类继承
class Person{ constructor(name,age){ this.name = name; this.age = age } sayName(){ console.log(this.name); }}class Teacher extends Person{ // 类继承之后,构造函数第一行必须写super关键字,去继承父类的属性 constructor(name,age,skill){ super(name,age) this.skill = skill } // 在子类的方法中调用父类的方法 (this或super去调用) show(){ super.sayName() // this.sayName() }}var t = new Teacher("zhang",18,"js")console.log(t);t.sayName()
1-4 静态属性和静态方法
通过 static 关键字定义静态方法和属性,不能在类的实例上调用静态方法,而应该通过类本身调用属于类所独有的特点:通过类名去调用
1-4-1 静态属性
class Person{ static BaseUrl = "https://www.baidu.com";}console.log(Person.BaseUrl) // 通过类名去调用
1-4-2 静态方法
class Person{ constructor(name,age){ this.name = name this.age = age } static sayName(){ console.log("name"); }}var p = new Person("lisi",19)console.log(p);Person.sayName()
1-4-2-1 静态方法和普通函数
1.在普通函数中能调用静态方法2.在静态方法中不能调用普通方法
class Person{ constructor(name,age){ this.name = name this.age = age } sayAge(){ Person.sayName() console.log(this.age); } static sayName(){ // 在静态方法中,this指-->调用静态方法的类 // this.sayAge() //在静态方法中不能调用普通方法 console.log("name"); console.log(this); // Person }}var p = new Person("name",18)Person.sayName()
1-5 继承静态方法和静态属性
1.子类可以继承父类的静态方法2.在子类的静态方法中调用父类的静态方法,用super和this去调用
class Person{ static BaseUrl = "https://www.baidu.com" static sayName(){ console.log("name"); }}class Teacher extends Person{ static show(){ super.sayName() // this.sayName() console.log(super.BaseUrl); }}// Teacher.sayName()Teacher.show()
1-6 总结
1.静态方法:静态方法是类所独有的,类创建的时候,就会在内存中存在,不用实例化, 直接通过类名调用,不会造成系统资源的格外浪费2.不可以在静态方法中调用普通方法3.在静态方法中,this指调用静态方法的类4.在普通方法中,this指实例化的对象5.静态方法是可以被继承的