前言
这东西私下学了n遍了,还是老记不住,这次空闲时间在学习react,常用到class,好记性不如烂笔头啊,所以专门记录一下,方便之后查看;
正文
1. 普通函数
// func语法
function Demo(x, y) {
this.x = x
this.y = y
}
Demo.prototype.test = function () {
return `${this.x}是X的值,${this.y}是Y 的值`
}
let str = new Demo(2, 3).test()
console.log(str)//2是X的值,3是Y 的值
2. 使用class改写
class Demo2 {
constructor(x, y) {
this.x = x
this.y = y
}
test() {
return `${this.x}是X的值,${this.y}是Y 的值`
}
static chanage() {
return '测试是否能被继承'
}
}
let str2 = new Demo2(5, 6).test()
let str3 = Demo2.chanage(2)
// let str4 = new Demo2(5, 6).chanage()//error 不能被继承
console.log(str2)//5是X的值,6是Y 的值
console.log(str3)//测试是否能被继承
2.1 class特征
使用class改写——class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。对比可知,test() class中的所有方法都定义在类的prototype属性上,多个属性不可枚举;
- constructor 是构造函数,new的时候自动调用,不写会默认添加一个空的constructor(){},默认返回实例对象(this);
- 调用方式,new Demo2(1,2);
- 类不存在变量提升;
- static 静态方法,不会被实例继承,而是直接通过类来调用;
3. class继承
class Demo3 {
constructor(x, y) {
this.x = x
this.y = y
}
test() {
return `${this.x}是X的值,${this.y}是Y 的值`
}
static isChanage() {
return '测试是否能被继承'
}
}
class Child1 extends Demo3 {
constructor(x, y, z) {
super(x, y)
// console.log(super.test(),'1');
this.z = z
}
toAdd() {
return `${this.z}是z的值,${this.y + this.z + this.x}是和的值`
}
}
let str4 = new Child1(5, 6, 7).test()
let str5 = new Child1(5, 6, 7).toAdd()
console.log(str4); //5是X的值,6是Y 的值
console.log(str5); //7是z的值,18是和的值
// let str6 = new Child1(5, 6, 7).isChanage() //error
let str6 = Child1.isChanage()
console.log(str6);//测试是否能被继承
3.1 继承的特征
- class通过extends关键字的继承;
- 子类必须先调用super方法,拿到this 对象,才能做其他操作,在普通方法中指向父类原型对象,可以取到父类的属性;
- static 静态方法,会被子类继承,可以直接调用;
4. super函数
未完。。。