class
class Fo {
constructor(a,b) {
this.x = a;
this.y = b;
}
gimmeXY() {
return this.x * this.y;
}
}
等价于如下代码
function Fo(a, b) {
this.x = a;
this.y = b;
}
Fo.prototype.gimmeXY = () => this.x * this.y;
以上两种方式的区别
2.extends和super
class Bar extends Fo {
constructor(a, b, c) {
super(a, b, c);
this.z = c;
}
gimmeXYZ() {
return super.gimmeXY() * this.z;
}
}
class ParentA {
constructor() {
this.id = "a";
}
foo() {
console.log("ParentA:", this.id);
}
}
class ChildA extends ParentA {
foo() {
super.foo();
console.log("ChildA:", this.id);
}
}
var a = new ChildA();
a.foo(); // Parent: a
// ChildA: a
class ParentB {
constructor() {
this.id = "b";
}
foo() {
console.log("ParentB:", this.id);
}
}
class ChildB extends ParentB {
foo() {
super.foo();
console.log("ChildB:", this.id);
}
}
var b = new ChildB();
b.foo(); // ParentB: b
// ChildB: b
b.foo.call(a); // ParentB: a
// ChildB: a
// this.id被动态绑定,super.foo()并没有被动态绑定
3.子类构造器
类和子类的构造器并不是必须的;省略的话会自动提供一个默认构造器
默认构造器可以认为是这样的
constructor(...args) {
super(...args);
}
1) 子类构造器中调用super(...)之后才能访问this(机制,可以理解为对实例中this进行创建/实例化的是父构造器
class Foo {
constructor() { this.a = 1; }
}
class Bar extends Foo {
constrcutor() {
this.b = 2; //不允许在super()之前使用this
super(); // Uncaught SyntaxError: 'super' keyword unexpected here
}
}
原文:https://www.cnblogs.com/wydumn/p/11788040.html