class a {
constructor(x, y){
this.x = x;
this.y = y;
}
static print(){
console.log(‘打印中…’);
}
}
// b类继承a类
class b extends a{
constructor(x, y, z){
super(x, y);
this.z = z;
}
}
let c = new b();
b.print();
Object.getPrototypeOf(b) === a
-
super:调用父类的constructor里面的属性和方法(必须调用一次)
-
父类的静态方法,也会被子类继承
-
在子类使用this前必须先调用一次super父类
-
Object.getPrototypeOf
方法可以用来从子类上获取父类
回到顶部 目录
super实际就是:a.prototype.constructor.call(this)
class A {
constructor() {
console.log(new.target.name);
}
}
class B extends A {
constructor() {
super();
}
}
new A() // A
new B() // B
-
super()内部的this指向的调用者(子类)
-
super只能放在子类的constructor方法中,不然就报错
-
如果super做为对象,在静态方法中,这时的super指向父类,而不是父类的原型
-
类的方法就是静态方法带
static的方法
-
类继承中:静态方法对静态方法,普通方法对普通方法(super所在的地方)
-
由于super使得this指向B的实例,所以super.valueOf()返回的是一个B的实例
-
子类的__proto__属性,表示构造函数的继承,总是指向父类的
-
子类的prototype属性的__proto__属性,表示方法的继承,总是指向父类的prototype属性
class A {}
class B extends A {}
console.log(B.proto) // class A {}
console.log(B.prototype.proto == A.prototype) // true
回到顶部 目录
重写类的继承
class A {}
class B {}
// B的实例继承A的实例
Object.setPrototypeOf(B.prototype, A.prototype);
// B继承A的静态属性
Object.setPrototypeOf(B, A);
// Object.setPrototypeOf实现方法
Object.setPrototypeOf = function (obj, proto){
obj.protr = proto;
return obj;
}
ECMAScript的原生构造函数有:
-
Boolean()
-
Number()
-
String()
-
Array()
-
Date()
-
Function()
-
RegExp()
-
Error()
-
Object()
在ES6以前这些原生构造函数是无法继承的:
// 编写一个myArray继承Aarry的方法
常用的JavaScript设计模式
-
单体模式
-
工厂模式
-
例模式
函数
-
函数的定义
-
局部变量和全局变量
-
返回值
-
匿名函数
-
自运行函数
-
闭包