码迷,mamicode.com
首页 > 编程语言 > 详细

[Javascript] ES6 Class Constructors and the Super Keyword

时间:2019-12-08 00:47:28      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:bec   called   util   script   require   ecif   function   struct   cti   

When the ES6 class shipped back in 2015, a number of additional keywords came with it. Two of these are constructor and super. Both of these are specific to the class keyword and make working with classes manageable. Both are utilized when the new keyword is used to create a new instance of a classconstructors are called initially with the new keyword and super is how a subclass can utilize it‘s parent‘s methods (like it‘s parent‘s constructor function) within that child class

 

You have to call super() function when you extends one class:

class Rectangle {
  constuctor(height, width) {
    this.name = ‘Rectangle‘
    this.height = height
    this.width = width
  }
}

class Square extends Rectangle {
  constructor(length) {
  super(length, length)
  this.name = ‘Square‘
  }
}

const myShape = new Square(1)

console.log(myShape)

 

Again, even if our rectangle class did not have a constructor, we‘d still need to call super within the square‘s constructor because it is required when we‘re working with subclasses that have constructors and when the this keyword is used in the constructor.

class Rectangle {

}

class Square extends Rectangle {
  constructor(length) {
     super()
     this.name = ‘Square‘
  }
}

 

[Javascript] ES6 Class Constructors and the Super Keyword

标签:bec   called   util   script   require   ecif   function   struct   cti   

原文地址:https://www.cnblogs.com/Answer1215/p/12003924.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!