gpt4 book ai didi

javascript - ES6构造函数继承

转载 作者:搜寻专家 更新时间:2023-11-01 05:30:14 24 4
gpt4 key购买 nike

我正在研究 ES6,因为它似乎在编写 reactJS 应用程序时得到提升。我对构造函数的工作方式感到有点惊讶:

class Human{ 
constructor(name){
this.name = name;
}
toString(){
return "Name = " + this.name;
}
}

class Person extends Human{}

var person = new Person("kim");

使用基于类的系统在 JS 中编写前端应用程序时,以下其中一项可能会使我的应用程序变得脆弱的可能性有多大:

  • 带参数的构造函数是隐式继承的(这总体上是个好主意吗?它保持这种状态的可能性有多大?);
  • 无法在同一类中重载构造函数;
  • 无法根据参数类型进行重载;

可选问题:
我的第二个问题是今天将 ES6 用于大型生产应用程序的决定有多聪明,以及现在仅使用 ES6 进行试验是否有用。我不确定认为 JS 正在朝着像 Java 这样的成熟的基于类的系统发展,并且事情可能比我的代码库能够消化的速度更快地改变(演变)。

最佳答案

Parametered constructors are implicitly inherited - is this a good idea overall and what is the chance that it will stay like that?

是的,它会一直这样。如果您没有提供构造函数,默认情况下是使用所有参数调用父构造函数。

这是个好主意,因为 class 确实要求您在构造函数中调用 super()(这至少对于继承 builins 是必要的,并且是一个好习惯反正)。如果没有默认构造函数,您必须自己明确提供它,这会导致样板代码的增加(class 关键字的目的是避免这种情况)。

Disability to overload constructors within the same class; Disability to overload based on parameter types

没有。当然,在 JS 中,一个类不能有多个构造函数,但是 you can still overload it ,包括传递参数的数量及其类型。

Is ES6 production-ready?

是的。标准被采用,没有更多的实验。转译器确实支持所有主要有用的语法功能。

I'm not sure whether it's misplaced to think that JS is tending towards a full fledged class based system like Java

是的,这是错误的。 JS 没有类似 Java 的类系统,而且几乎永远不会有。另见 Will JavaScript ever become a 'proper' class based language? .

关于javascript - ES6构造函数继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32169631/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com