我正在上课。
class A {
constructor() {
}
getThis() {
return this;
}
}
class B extends A {
constructor() {
super();
this.superclass = super; // SyntaxError: 'super' keyword unexpected here
this.superclass = super.getThis(); // this.superclass is this(B and not A)
}
}
Run Code Online (Sandbox Code Playgroud)
如何访问超类(不是属性或方法)?
编辑:
class A {
constructor() {
this.a = 1;
}
getThis() {
return this;
}
}
class B extends A {
constructor() {
super();
this.b = 2;
console.log( [get the super class] ); // A { a: 1 }
console.log(this); // B { a: 1, b: 2 }
}
}
Run Code Online (Sandbox Code Playgroud)
有没有可能用数据获取超类?
这样做对您没有任何用处的情况很少见,但是在使用class
语法时有几种方法:
您可以获得以下原型B
:
Object.getPrototypeOf(B) === A // true
Run Code Online (Sandbox Code Playgroud)
这是有效的,因为class
语法将A
构造函数指定为构造函数的原型B
(这很方便,这意味着B
从 继承静态方法A
)。
或者您可以通过获取 constructor
的原型的属性来实现B.prototype
:
Object.getPrototypeOf(B.prototype).constructor === A // true
Run Code Online (Sandbox Code Playgroud)
或者,如果您想使用 istanceB
作为起点(this
在本例中):
Object.getPrototypeOf(Object.getPrototypeOf(this)).constructor === A // true
Run Code Online (Sandbox Code Playgroud)
现场示例:
Object.getPrototypeOf(B) === A // true
Run Code Online (Sandbox Code Playgroud)
不过,你getThis
暗示了一个误解。当您new B
创建 的实例时B
,不会创建一个单独的对象,它只是 的一个实例A
。new B
创建的一个对象是继承和初始化的特性A
和B
结果的组合。没有单独的A
实例。(有A.prototype
,但那不是 的实例A
,它只是用作 的实例的原型的对象A
。)
重新编辑:
有没有可能用数据获取超类?
我认为您的意思是“是否可以使用数据获取超类的实例?” 答案是或否取决于您想如何看待它。的实例B
是的实例A
,因此从这个意义上说,“是”,因为您已经拥有它,因为您拥有 的实例B
。但是没有单独的实例A
,只有一个A
而不是一个B
(见上文),所以从这个意义上说,“不”。
使用A
andB
在你的编辑中,在做之前new B
,你在内存中有这样的东西,基本上是两个构造函数A
andB
和它们关联的A.prototype
andB.prototype
对象:
+??????????????????????????????????????????????????? ??????+ | | v | +???????????????+ | A?????>| 功能 A | +?>Function.prototype | +???????????????+ | | | [[原型]] |??+ | | 名称: "A" | +???????????????+ | | 原型|????>| A.prototype | | +???????????????+ +???????????????+ | ^ | [[原型]] |?????>Object.prototype | | | 构造函数|??????????????????????????????+ | +???????????????+ +????????????+ ^ | | +???????????????+ | +????????????+ B?????>| 功能 B | | | +???????????????+ | | | [[原型]] |??+ | | 名称: "B" | +???????????????+ | | 原型|????>| B.原型| | +???????????????+ +???????????????+ | ^ | [[原型]] |??+ | | 构造函数|??+ | +???????????????+ | | | +?????????????????????????????????????+
(省略了一些细节。)
现在,如果你这样做:
const b = new B();
Run Code Online (Sandbox Code Playgroud)
创建单个对象。该A
构造增加了一个a
属性,以新的对象,而B
构造函数添加一个b
属性到新的对象:
+???????????????+ b?????>| B的实例| +???????????????+ | [[原型]] |????>B.prototype | 答:1 | | 乙:2 | +???????????????+
它是一个单独的对象,而不是包含a
和的单独对象b
。在this
该A
“s中的代码的用途this.a = 1
是相同的对象this
即B
”在S码的用途this.b = 2
。
归档时间: |
|
查看次数: |
220 次 |
最近记录: |