ClassName.variable 总是一个静态成员变量吗?

Is ClassName.variable always a static member variable?

我从未见过像下面这样的语法,其中通过附加到 class 名称直接初始化变量(静态成员除外)

class Fruit {
  constructor(color) {
    this.color = color;
  }
}
Fruit.count = 0;

这个 count 变量在内存中的什么位置?我无法使用 class 实例访问它。那么,它是隐含的静态成员吗​​?它在 Classical Prototypal Inheritance 中会是什么样子?提前致谢。

任何直接分配给 class 的 属性,与 Fruit.count = 0; 一样,被认为是有效分配 static variable/member.一个实际上使用 constructor 作为命名空间。

例子...

class Fruit {
  constructor(color) {
    this.color = color;
  }
}
Fruit.count = 0;

console.log('considered to be "static" ... Fruit.count :', Fruit.count);

const fruitType = new Fruit('yellow');

console.log('fruitType.constructor.count :', fruitType.constructor.count);

class Fruit {
  constructor(color) {
    this.color = color;
  }
  static count = 42;
}

console.log('literally "static" ... Fruit.count :', Fruit.count);

const fruitType = new Fruit('red');

console.log('fruitType.constructor.count :', fruitType.constructor.count);

function Fruit(color) {
  this.color = color;
}
Fruit.count = 9;

console.log('old school "static" ... Fruit.count :', Fruit.count);

const fruitType = new Fruit('pink');

console.log('fruitType.constructor.count :', fruitType.constructor.count);

How will it look in Classical Prototypal Inheritance?

StaticPrototypal 没有任何共同点。因此,最后一个问题不会有任何有效答案。

但如果 OP 指的是 “经典原型继承” 到 ES3 语法,那么第三个示例代码已经回答了它。

class Fruit {
  constructor(color) {
    this.color = color;
  }
  static s = 1
}

Fruit.count = 0
const f = new Fruit('red')

countsFruit 对象的属性。 console.dir(Fruit) 结果为 -

class Fruit
  count: 0
  s: 1
  arguments: (...)
  caller: (...)
  length: 1
  name: "Fruit"
  prototype: {constructor: ƒ}
  __proto__: ƒ ()
  [[FunctionLocation]]: VM924:2
  [[Scopes]]: Scopes[2]

在上面的输出中,Fruit.prototype.constructorFruit 相同,即 Fruit.prototype.constructor === Fruittrue

console.dir(f) 结果为 -

Fruit
  color: "red"
  __proto__:
    constructor: class Fruit
    __proto__: Object

从这个 class 构造新对象时,Fruit.prototype 变为 f.__proto__。所以 Fruit.prototype === f.__proto__true.

因此您可以通过f.__proto__.constructor.count访问静态属性。由于 __proto__ 上的属性直接继承到实例,您可以通过 f.constructor.count.

访问它们