我发现类的静态成员由 JavaScript 中的子类继承。我已经使用 Chrome 67.0.3396.62
、FireFox 60.0.1
和
NodeJS 10.1.0
.
但是在 OOP 中,静态成员和字段应该属于类而不是被继承,这不是很奇怪吗?
这是 JavaScript extends
的错误吗?
class A {
static a () {
console.log('==[static a]==')
}
}
A.propA = { anything: '==[static data from A]==' }
class B extends A { }
console.log(B.a()) // "==[static a]=="
console.log(B.propA.anything) // "==[static data from A]=="
最佳答案
Is it a bug for JavaScript
extends
?
不,它完全按照设计工作。
So where did class
B
actually find its inheritedpropA
property? Through which part of the prototype chain?
让我们首先澄清两件事:
- 函数是对象,这意味着它们有一个原型(prototype)。默认情况下是
Function.prototype
,它是定义.call
和.apply
等方法的地方。 - “静态成员”只是函数对象的属性
做的时候
class B extends A {}
然后为 B
创建一个新的函数对象,其原型(prototype)值为 A
,而不是 Function.prototype
,因此A
的所有属性都可以通过 B
访问。
我们可以轻松验证这一点:
class A {}
class B extends A {}
console.log(Object.getPrototypeOf(B) === A);
关于javascript - ES6静态成员被子类继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50713575/