Skip to main content

3 posts tagged with "es6"

View All Tags

Promise

· 3 min read
Lex
Front End Engineer @ Baoxiaohe
  • What's Promise?
  • Why the Promise?
  • How using Promise?

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.

Why use let instead of var

· One min read
Lex
Front End Engineer @ Baoxiaohe

🆗,我相信大家都知道变量提升。like this👇

console.log(variate);let variate = 10;
Error

Uncaught ReferenceError: variate is not defined

console.log(variate); // undefinedvar variate = 10;

很好理解,因为var存在变量提升,上面的代码摇身一变:

var variate;console.log(variate); // undefinedvariate = 10;
可问题是,真实开发中谁会写这样的代码呢?因为先定义再使用变量符合正常的逻辑。仅仅为了少数可能的不正常脑回路的忍者代码似乎没必要单独加一个 let 语法。

所以,更值得探讨的是let块级作用域