super()和super(props)
一、ES6类
在ES6
中,通过extends
关键字实现类的继承,方式如下:
class sup { constructor(name) { this.name = name } printName() { console.log(this.name) } } class sub extends sup{ constructor(name,age) { super(name) // super代表的事父类的构造函数 this.age = age } printAge() { console.log(this.age) } } let jack = new sub('jack',20) jack.printName() //输出 : jack jack.printAge() //输出 : 20
在上面的例子中,可以看到通过super
关键字实现调用父类,super
代替的是父类的构建函数,使用super(name)
相当于调用sup.prototype.constructor.call(this,name)
如果在子类中不使用super
,关键字,则会引发报错,如下:
报错的原因是 子类是没有自己的this
对象的,它只能继承父类的this
对象,然后对其进行加工
而super()
就是将父类中的this
对象继承给子类的,没有super()
子类就得不到this
对象
如果先调用this
,再初始化super()
,同样是禁止的行为
class sub extends sup{ constructor(name,age) { this.age = age super(name) // super代表的事父类的构造函数 } }
所以在子类constructor
中,必须先调用super
才能引用this
二、类组件
在React
中,类组件是基于es6
的规范实现的,继承React.Component
,因此如果用到constructor
就必须写super()
才初始化this
这时候,在调用super()
的时候,我们一般都需要传入props
作为参数,如果不传进去,React
内部也会将其定义在组件实例中
// React 内部 const instance = new YourComponent(props); instance.props = props;
所以无论有没有constructor
,在render
中this.props
都是可以使用的,这是React
自动附带的,是可以不写的:
class HelloMessage extends React.Component{ render (){ return ( <div>nice to meet you! {this.props.name}</div> ); } }
但是也不建议使用super()
代替super(props)
因为在React
会在类组件构造函数生成实例后再给this.props
赋值,所以在不传递props
在super
的情况下,调用this.props
为undefined
,如下情况:
class Button extends React.Component { constructor(props) { super(); // 没传入 props console.log(props); // {} console.log(this.props); // undefined // ... }
而传入props
的则都能正常访问,确保了 this.props
在构造函数执行完毕之前已被赋值,更符合逻辑,如下:
class Button extends React.Component { constructor(props) { super(props); // 没传入 props console.log(props); // {} console.log(this.props); // {} // ... }
三、总结
在React
中,类组件基于ES6
,所以在constructor
中必须使用super
在调用super
过程,无论是否传入props
,React
内部都会将porps
赋值给组件实例porps
属性中
如果只调用了super()
,那么this.props
在super()
和构造函数结束之间仍是undefined
本文来自博客园,作者:喆星高照,转载请注明原文链接:https://www.cnblogs.com/houxianzhou/p/15047559.html
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?