1.object assign
class Person{constructor(name,age){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 s=new Person("meng", 21);s.sayAge()
方法:Object assign
Object.assign(Person.prototype,{sayAge(){console.log(this.age)},show(){console.log("show")}})
2.私有属性
class Person{skill="css"//默认为私有属性constructor(name,age){this.name=name;this.age=age;}sayName(){console.log(this.name)}}var s=new Person("meng",21);console.log(s)
3.class extends类继承
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("meng",21,"css");t.show();console.log(t)
4.static 静态
//静态属性,静态方法
// 属于类所独有的 特点:通过类名去调用
4.1静态属性
class Person{static BaseUrl = "https://www.baidu.com";}console.log(Person.BaseUrl) // 通过类名去调用
4.2静态方法
class Person{constructor(name,age){this.name=name;this.age=age;}static sayName(){console.log("name")}}var s=new Person("meng",21);Person.sayName();
4.3静态方法和普通方法
//普通方法可以调用静态方法(用类名调用)
// 静态方法不能调用普通方法
class Person{constructor(name,age){this.name=name;this.age=age;}sayAge(){Person.sayName();console.log(this.age);}static sayName(){this.sayAge()console.log("name")}}var s=new Person("meng",21);s.sayAge();Person.sayName();
5. static-this
/* 静态方法:1.静态方法是属于类所独有的,类创建的时候,就会在内存中存在。不用实例化,直接通过类名直接调用,不会造成系统资源的格外浪费2.不可以在静态方法中,调用普通方法3.静态方法中的this,指调用静态方法的这个类4.静态方法是可以被继承的*//* 在静态方法中this指-->调用静态方法的类*/class Person{constructor(name,age){this.name=name;this.age=age;}sayAge(){Person.sayName();console.log(this.age);}static sayName(){console.log(this) /在静态方法中this指-->调用静态方法的类(Person)/console.log("name")}}Person.sayName();
6.静态方法和继承
/*1.子类可以继承父类的静态方法2.在子类的静态方法中调用父类的静态方法,可以通过this,super调用*/class Person{static baseUrl="http://www.baidu.com"static sayName(){console.log("name")}}class Teacher extends Person{static sayAge(){super.sayName();console.log(this.baseUrl)console.log("age")}}Teacher.sayName()Teacher.sayAge()console.log(Person.baseUrl)
