码迷,mamicode.com
首页 > 其他好文 > 详细

es6 class

时间:2017-06-19 19:43:55      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:selector   tostring   bsp   es6   class   加工   pre   const   type   

    ES6的class可以看作只是一个语法糖,它的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。

 

function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
  return ‘(‘ + this.x + ‘, ‘ + this.y + ‘)‘;
};
等同于

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return ‘(‘ + this.x + ‘, ‘ + this.y + ‘)‘;
  }
}

在 JavaScript 中,每个对象都有原型对象。所有 JavaScript 对象都从原型上继承方法和属性。
ES5中,属性放在构造函数(constructor)里,方法放在原型(prototype)上;
ES6中引入了类(class)来代替构造函数(constructor);

 

在之类的constructor中必须调用 super方法,子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。super代表了父类构造函数。对于你的实例相当于执行Component(props)。但是注意,此处this指向 子类。更严谨的是相当于

Component.prototype.constructor.call(this,props)。

至于为什么一定要有super?可以很容易想得到,先有父才有子嘛。super继承父类属性,在constructor中进行自己的改造。如果在constructor中使用到this,必须在使用this之前调用super()。

 

es6 class

标签:selector   tostring   bsp   es6   class   加工   pre   const   type   

原文地址:http://www.cnblogs.com/lmyt/p/7049940.html

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