class Person{
// 构造方法,调用new,自动执行
constructor(name,age){
this.name=name;
this.age=age;
}
// 等价于 Person.prototype.showname
showname(){
console.log(`名字是${this.name}`);
}
}
let p1=new Person('aaaa',12);
// 表达式形式
const Person=class{
// 构造方法,调用new,自动执行
constructor(name,age){
this.name=name;
this.age=age;
}
}
let p1=new Person('aaaa',12);
// 变量定义方法名
let aaa='ssss';
class Person{
// 构造方法,调用new,自动执行
constructor(name,age){
this.name=name;
this.age=age;
}
// 变量定义方法名
[aaa](){
return 'ok'
}
}
let p1=new Person('aaaa',12);
console.log(p1[aaa]());//ok
console.log(p1.ssss());//ok
// class没有提升功能
let p1=new Person('aaaa',12);//error:Person is not defined
class Person{
// 构造方法,调用new,自动执行
constructor(name,age){
this.name=name;
this.age=age;
}
}
class Person{
constructor(name,age){
this.name=name;
this.age=age;
// 改变this指向
this.showname=this.showname.bind(this);
}
showname(){
console.log(this);
console.log(`名字是${this.name}`);
}
}
let p1=new Person('aaaa',12);
let {showname}=p1;
showname();
class Person{
constructor(){
}
set aaa(val){
console.log(`设置aaa属性,值为${val}`)
}
get aaa(){
return 'ass';
}
}
let p1=new Person();
p1.aaa=123; //设置aaa属性,值为123
console.log(p1.aaa);//ass
// 静态方法:类身上的方法 static
class Person{
constructor(){
}
static test(){
console.log('静态方法');
}
}
Person.test();//静态方法
// 父类
class Person{
constructor(name){
this.name=name;
}
showname(){
console.log(this.name);
}
}
// 子类
class Student extends Person{
constructor(name,grade){
super(name);//super指代父级 super
作为函数调用时,代表父类的构造函数,super()
只能用在子类的构造函数之中
this.grade=grade;
}
showname(){
super.showname();//父级的方法执行 super
作为对象时,在普通方法中,指向父类的原型对象;在静态方法中,指向父类。
console.log('子类');
}
showgrade(){
console.log(this.grade);
}
}
let stu1=new Student('aaa','一年级');
stu1.showname();//aaa 子类
stu1.showgrade();//一年级
// super指向父类的原型对象,所以定义在父类实例上的方法或属性,是无法通过super调用的
class A {
constructor() {
this.p = 2;
}
}
class B extends A {
get m() {
return super.p;
}
}
let b = new B();
b.m // undefined
// 如果super作为对象,用在静态方法之中,这时super将指向父类,而不是父类的原型对象。
class Parent {
static myMethod(msg) {
console.log('static', msg);
}
myMethod(msg) {
console.log('instance', msg);
}
}
class Child extends Parent {
static myMethod(msg) {
super.myMethod(msg);
}
myMethod(msg) {
super.myMethod(msg);
}
}
Child.myMethod(1); // static 1
var child = new Child();
child.myMethod(2); // instance 2