Skip to main content

Extends in JavaScript

· One min read
Lex
Front End Engineer @ Baoxiaohe

Class in ES6#

ES6(May ES6,7...)新增了Class语法,似乎使得 JavaScript 能像 Java 一样使用继承语法了。

class Person{  constructor(name,age) {    this.name = name    this.age = age  }    running(){    console.log("yep,i am running")  }}
class Student extends Person{  constructor(name,age,sno) {    super(name,age);    this.sno = sno  }}

transform to ES5#

var Person = /*#__PURE__*/function () {  function Person(name, age) {    _classCallCheck(this, Person);
    this.name = name;    this.age = age;  }
  _createClass(Person, [{    key: "running",    value: function running() {      console.log("yep,i am running");    }  }]);
  return Person;}();
var Student = /*#__PURE__*/function (_Person) {  _inherits(Student, _Person);
  var _super = _createSuper(Student);
  function Student(name, age, sno) {    var _this;
    _classCallCheck(this, Student);
    _this = _super.call(this, name, age); // 通过 call 绑定 this     _this.sno = sno;    return _this;  }
  return Student;}(Person);

🕵️‍♂️

可以看到 子类 Student 通过调用 call 函数将父类构造函数中的 this 绑定为自身,相当于在自身调用

this.name = namethis.age = agethis.sno = sno

So,Class 语法本质上还是 function.

Function is a first-class citizen in JavaScript.