JavaScript ES6类扩展没有超 [英] Javascript ES6 class extend without super

查看:117
本文介绍了JavaScript ES6类扩展没有超的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在ES6中扩展类,而不调用 super 方法来调用父类?

Is it possible to extend a class in ES6 without calling the super method to invoke the parent class?

编辑:这个问题可能是误导。是否是我们必须调用 super()或我缺少某些东西的标准?

The question might be misleading. Is it the standard that we have to call super() or am I missing something?

例如:

class Character {
   constructor(){
      console.log('invoke character');
   }
}

class Hero extends Character{
  constructor(){
      super(); // exception thrown here when not called
      console.log('invoke hero');
  }
}

var hero = new Hero();

当我不调用 super()对派生类我得到范围问题 - > 这没有定义

When I'm not calling super() on the derived class I'm getting a scope problem -> this is not defined

这与iojs --harmony在v2.3.0

I'm running this with iojs --harmony in v2.3.0

推荐答案

ES2015(ES6)类的规则基本上归结为: p>

The rules for ES2015 (ES6) classes basically come down to:


  1. 中, 如果它们是子类,它们必须显式地调用。

  2. <返回一些对象以替代未初始化的对象。
  1. In a child class constructor, this cannot be used until super is called.
  2. ES6 class constructors MUST call super if they are subclasses, or they must explicitly return some object to take the place of the one that was not initialized.

这是ES2015规范的两个重要部分。

This comes down to two important sections of the ES2015 spec.

部分 8.1.1.3.4 定义了决定函数中 this 的逻辑。类的重要部分是, 可能处于未初始化状态,状态,尝试使用将抛出异常。

Section 8.1.1.3.4 defines the logic to decide what this is in the function. The important part for classes is that it is possible for this be in an "uninitialized" state, and when in this state, attempting to use this will throw an exception.

9.2.2 [[Construct]] ,它定义通过 new super 调用的函数的行为。当调用基类构造函数时, [[Construct]] 的第8步初始化其他情况下,未初始化。在构造结束时,调用 GetThisBinding ,因此如果 super 尚未被调用(因此初始化 this ),或者没有返回显式替换对象,构造函数调用的最后一行将抛出异常。

Section 9.2.2, [[Construct]], which defines the behavior of functions called via new or super. When calling a base class constructor, this is initialized at step #8 of [[Construct]], but for all other cases, this is uninitialized. At the end of construction, GetThisBinding is called, so if super has not been called yet (thus initializing this), or an explicit replacement object was not returned, the final line of the constructor call will throw an exception.

这篇关于JavaScript ES6类扩展没有超的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆