class 方法与 JS 中的 className.prototype 方法的区别

Difference between class method vs className.prototype method in JS

我想知道通过 Class body 设置方法与 JS 中的原型绑定之间有什么区别。 (如果有的话)

我目前正在研究 Eloquent JavaScript 示例,我很惊讶作者首先创建了一个 class 并在其主体中创建了一堆方法,然后使用 [= 创建了另一个方法13=]

class Cat {
    constructor() {
    }

    method1() {
      console.log("m1");
    }
}

Cat.protoype.method2 = function() {
  console.log("m2");
}

最明显的区别是:

你可以用第二种方法(包括原生的)改变每个 class 的原型,而第一种语法只适用于声明你自己的 classes(但另一方面它保持事物整洁有序)。

还有其他差异,在大多数情况下您可以忽略:

1) Class 方法 不可枚举 ,而直接设置 属性 使其 可枚举

这更等同于 class 语法:

  Object.defineProperty(Cat.protoype, "method2", {
     value() {
       console.log("m2");
      },
      enumerable: false, // it's the default value, this is just for clarity
      writable: true,
      configurable: true,
  });

2) super 只能在对象/class 本身的声明期间添加的方法中访问(在对象和 classes 中)。

3)函数的.name第一种是"test",第二种是"anonymous"。这可以通过使函数非匿名来改变,例如function method2() { ... }

希望对您有所帮助:"Changes to the Object prototype object are seen by all objects through prototype chaining, unless the properties and methods subject to those changes are overridden further along the prototype chain. This provides a very powerful although potentially dangerous mechanism to override or extend object behavior."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype