注意:
1、类名:大驼峰 (ExampleProject)
2、方法名:小驼峰 (changeProjectName)
一、普通属性
class Test {
constructor(props) {
...
}
call() {
...
}
}
let onePlus = new Test("aaa","bbb"); // onePlus:对象 Test:类
onePlus.call(); // 对象调用
总结:
1、先class 后new
2、new后面的是类
3、普通属性 对象调用
二、静态属性(static)
class Phone {
static name="手机";
static change() {
...
}
}
let onePlus = new Phone();
console.log(Phone.name); // 正确调用 类调用
console.log(onePlus.name); // 错误调用
总结:
1、静态属性 类调用
三、类继承
// 父类
class Phone {
constructor(brand,price) {
this.brand = brand;
this.price = price;
}
call() {
console.log("我可以打电话!");
}
}
// 子类
class SmartPhone extends Phone {
constructor(brand,price,color,size) {
super(brand,price); // Phone.call(this,brand,price);
this.color = color;
this.size = size;
}
photo() {
...
}
playGame() {
...
}
// 重写父类的方法
call() {
...
}
}
// 实例化对象
const xiaomi = new SmartPhone ('小米',1999,'黑色','4.7');
xiaomi.call();
xiaomi.photo();
xiaomi.playGame();
总结:
1、通过 extends 实现类的继承
2、子类声明一个和父类同名方法 称之为重写(如上述 call())
3、子类如果有call方法 就执行子类的 如果没有 就执行父类的
四、getter/setter
1、都放在子类中
class Phone {
get price() {
return this.price();
}
set price(val) {
if(val == 1){
this.price = 'a';
}else{
this.price = 'b';
}
}
}
//实例化对象
let s = new Phone();
s.price = 1; // a
2、同级出现
class Father {
constructor() { }
get a() {
return this._a;
}
}
class Child extends Father {
constructor() {
super();
}
set a(a) {
this._a = a;
}
}
let test = new Child();
test.a = 2;
console.log(test.a); // undefined
注意:
1、getter不能单独出现
2、getter与setter 必须同级出现
五、super
普通方法
1.调用父类的构造函数,只能出现在子类的构造函数
// 父类
class Father {
test() {
return 0;
}
static test1() {
return 1;
}
}
// 子类
class Child extends Father {
//构造函数
constructor(a) {
super();
this.a = a;
}
}
总结:
1、constructor 方法是类的默认方法 创建类的实例化对象时被调用
2、子类 constructor 方法中必须有 super 且必须出现在 this 之前
静态方法
2.调用父类方法,super作为对象,在普通方法中,指向父类的原型对象
// 父类
class Father {
test() {
return 0;
}
static test1() {
return 1;
}
}
// 子类
class Child extends Father {
constructor() {
super();
console.log(super.test()); // 0
}
static test2() {
//调用父类的静态方法
return super.test1+2;
}
}
Child.test2(); // 3
总结:
1、在普通方法中 super指向父类的原型对象
2、在静态方法中 super指向父类
注意:
1、constructor方法是类的默认方法,子类中必须有super,且必须出现在this之前
2、如果constructor中使用this.props,则super(props)
3、无论有没有constructor,this.props可以使用