简单学ES6 - class

前言

随着ES6标准的定稿,众多的特性也趋于稳定,各大浏览器也在逐步实现这些特性,那么对ES6有更多的了解就无可厚非了。

准备

在学习ES6之前,我们需要有一个环境来测试ES6代码。在这里我推荐使用node的分支io.js。

  1. 如何安装?

    1. 下载地址:https://iojs.org/en/index.html,如果各位小伙伴不习惯英文,可以把url中的en修改为cn。
    2. 然后根据自己的操作系统版本,下载合适的安装包(主要指Windows系统)进行安装。
    3. 安装过程就不一一赘述了,和一般软件一样。
  2. 如何验证安装成功?
    1. 打开cmd,然后输入iojs -v,如果输出一个版本号,那么就代表io.js安装成功。(PS:我现在使用的是v1.2.0)
    2. 也可以输入iojs -p process.versions.v8查看iojs所使用的V8(PS:不是V8发动机)的版本。(PS:我这儿显示4.1.0.14)

小窥ES6

在测试ES6代码前,我们可以先看下io.js对ES6的支持:https://iojs.org/cn/es6.html

接下来,开始我们的ES6-Class之旅:

1、class 基础

大家应该知道,在大部分面向对象的语言中,都有class的说法,那么在早期的Js中,面向对象的实现比较特殊,我们必须要用function来模拟。如:

//ES5及以下
function Point(x, y){
  this.x = x;
  this.y = y;
}
var p1 = new Point(100, 100);

然而在ES6中,我们可以直接使用class关键字,如:

//ES6
‘use strict‘ //不能去掉,要不然iojs会提示不认识class。
class Point{
  constructor(x, y){
    this.x = x;
    this.y = y;
  }
}
var p1 = new Point(100, 100);
console.log(p1);

将以上代码保存为1.js,那么执行如下命令:iojs --es_staging 1.js 就可以看到"{x:100, y: 100}"这个结果了。(PS:注意要在1.js的目录打开cmd)。

接下来,看一个复杂点的,继承:

//ES6
‘use strict‘
class Point{
  constructor(x, y){
    this.x = x;
    this.y = y;
  }
}
var p1 = new Point(100, 100);
console.log(p1);

class ColorPoint extends Point{
  constructor(x, y, color){
    super(x, y);
    this.color = color;
  }
}
var cp = new ColorPoint(50, 50, ‘red‘);
console.log(cp);

//输出继承关系
console.log(cp instanceof ColorPoint); //true
console.log(cp instanceof Point);  //true

可以看到,和大部分语言的继承都很类似,如果你有其他面向对象语言的基础,那么很容易就能理解。

对Point和ColorPoint进行typeof,结果很明显也能看到是function。

console.log(typeof Point);  // function
console.log(typeof ColorPoint);  // function

那如果对class进行函数调用呢?

Point(100, 100); //Error

如上,必须通过new调用class,直接使用函数调用则会报错。

再来对比以下代码:

//标准的函数可以先写调用语句,后写申明语句。因为会定义前置
foo();
function foo(){}
//如果是class呢?
new Foo(); //Error,Foo is not defined
class Foo{}

如上,如果是定义的class,那么必须要定义语句在前,调用在后。

再来看以下的情形:

function funThatUseBar(){
  new Bar();
}
//funThatUseBar(); //Error,Bar is not defined
class Bar{}
funThatUseBar(); //ok

如上,如果先使用了Bar,那么也是会报错的。必须要优先定义class。

附上以上所有的js,会报错的语句,进行了注释。

//ES6
‘use strict‘
class Point{
  constructor(x, y){
    this.x = x;
    this.y = y;
  }
}
var p1 = new Point(100, 100);
console.log(p1);

class ColorPoint extends Point{
  constructor(x, y, color){
    super(x, y);
    this.color = color;
  }
}
var cp = new ColorPoint(50, 50, ‘red‘);
console.log(cp);

//*********************************************

//输出继承关系
console.log(cp instanceof ColorPoint); //true
console.log(cp instanceof Point);  //true

console.log(typeof Point);  // function
console.log(typeof ColorPoint);  // function

//Point(100, 100); //Error

//************************************
//标准的函数可以先写调用语句,后写申明语句。因为会定义前置
foo();
function foo(){}

//如果是class呢?
//new Foo(); //Error,Foo is not defined
class Foo{}

//*******************************************

function funThatUseBar(){
  new Bar();
}
//funThatUseBar(); //Error,Bar is not defined
class Bar{}
funThatUseBar(); //ok

2、类中的主体

ES6中、class的主体只能包含方法,不能包含数据属性。如果在类中包含变量定义,则会报错。class中的方法有三种类型:构造函数、静态方法、原型方法,如:

class Class1{
  //构造
  constructor(options){

  }

  // 静态方法,静态方法用static修饰
  static staticMethod(){
    return ‘static method‘;
  }

  prototypeMethod(){
    return ‘prototype method‘;
  }
}

其中,每个class和class原型的constructor都是相等的,同时class本质也是function

console.log(Class1 === Class1.prototype.constructor) // true
console.log(typeof Class1)  // function

然后我们对类中的方法做测试

var p = console.log;
p(typeof Class1.prototype.prototypeMethod);
Class1.prototype.prototypeMethod() // 原型方法调用方式
p(typeof Class1.staticMethod);
Class1.staticMethod() //静态方法调用方式

Getters 和 Setters 的用法

class Class2{
  get name(){
    return ‘jay‘;
  }
  set name(value){
    console.log(‘set name = ‘ + value);
  }
}

var c2 = new Class2();
c2.name = ‘hu‘;  // "set name = hu"
console.log(c2.name); // "jay"

当使用了get和set时,那么针对属性的get和set会自动调用class中相关的方法。

贴出所有Js代码:

‘use strict‘
class Class1{
  //构造
  constructor(options){

  }

  // 静态方法
  static staticMethod(){
    return ‘static method‘;
  }

  prototypeMethod(){
    return ‘prototype method‘;
  }
}

console.log(Class1 === Class1.prototype.constructor);
console.log(typeof Class1);

var p = console.log;
p(typeof Class1.prototype.prototypeMethod);
p(typeof Class1.staticMethod);

class Class2{
  get name(){
    return ‘jay‘;
  }
  set name(value){
    console.log(‘set name = ‘ + value);
  }
}

var c2 = new Class2();
c2.name = ‘hu‘;
console.log(c2.name);

3、类的继承

简单的继承关系,如下:

‘use strict‘
class Class1{
  toString(){
    return ‘parent class.‘;
  }
}

class SubClass extends Class1{
  toString(){
    return ‘sub class.‘;
  }
}

var sc = new SubClass();
console.log(sc.toString()); // "sub class"

其中,sc是Class1的实例,也是SubClass的实例:

console.log(sc instanceof Class1); //true
console.log(sc instanceof SubClass); //true

如果要调用父类的方法,怎么办呢?

class SubClass2 extends Class1{
  toString(){
    return super.toString();
  }
}

var sc2 = new SubClass2();
console.log(sc2.toString());

在继承关系中,子类的原型等于父类:

console.log(Object.getPrototypeOf(SubClass2) === Class1); //true

在子类中访问父类构造,使用super即可。

其他

  1. 如果想一览所有的ES6新特性,可以参考https://github.com/lukehoban/es6features
  2. 如果想系统的学习ES6,那么推荐http://es6.ruanyifeng.com/
  3. 想了解更多Classes in ECMAScript 6,可参考http://www.2ality.com/2015/02/es6-classes-final.html

*:first-child {
margin-top: 0 !important;
}

body>*:last-child {
margin-bottom: 0 !important;
}

/* BLOCKS
=============================================================================*/

p, blockquote, ul, ol, dl, table, pre {
margin: 15px 0;
}

/* HEADERS
=============================================================================*/

h1, h2, h3, h4, h5, h6 {
margin: 20px 0 10px;
padding: 0;
font-weight: bold;
-webkit-font-smoothing: antialiased;
}

h1 tt, h1 code, h2 tt, h2 code, h3 tt, h3 code, h4 tt, h4 code, h5 tt, h5 code, h6 tt, h6 code {
font-size: inherit;
}

h1 {
font-size: 28px;
color: #000;
}

h2 {
font-size: 24px;
border-bottom: 1px solid #ccc;
color: #000;
}

h3 {
font-size: 18px;
}

h4 {
font-size: 16px;
}

h5 {
font-size: 14px;
}

h6 {
color: #777;
font-size: 14px;
}

body>h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-child, body>h4:first-child, body>h5:first-child, body>h6:first-child {
margin-top: 0;
padding-top: 0;
}

a:first-child h1, a:first-child h2, a:first-child h3, a:first-child h4, a:first-child h5, a:first-child h6 {
margin-top: 0;
padding-top: 0;
}

h1+p, h2+p, h3+p, h4+p, h5+p, h6+p {
margin-top: 10px;
}

/* LINKS
=============================================================================*/

a {
color: #4183C4;
text-decoration: none;
}

a:hover {
text-decoration: underline;
}

/* LISTS
=============================================================================*/

ul, ol {
padding-left: 30px;
}

ul li > :first-child,
ol li > :first-child,
ul li ul:first-of-type,
ol li ol:first-of-type,
ul li ol:first-of-type,
ol li ul:first-of-type {
margin-top: 0px;
}

ul ul, ul ol, ol ol, ol ul {
margin-bottom: 0;
}

dl {
padding: 0;
}

dl dt {
font-size: 14px;
font-weight: bold;
font-style: italic;
padding: 0;
margin: 15px 0 5px;
}

dl dt:first-child {
padding: 0;
}

dl dt>:first-child {
margin-top: 0px;
}

dl dt>:last-child {
margin-bottom: 0px;
}

dl dd {
margin: 0 0 15px;
padding: 0 15px;
}

dl dd>:first-child {
margin-top: 0px;
}

dl dd>:last-child {
margin-bottom: 0px;
}

/* CODE
=============================================================================*/

pre, code, tt {
font-size: 12px;
font-family: Consolas, "Liberation Mono", Courier, monospace;
}

code, tt {
margin: 0 0px;
padding: 0px 0px;
white-space: nowrap;
border: 1px solid #eaeaea;
background-color: #f8f8f8;
border-radius: 3px;
}

pre>code {
margin: 0;
padding: 0;
white-space: pre;
border: none;
background: transparent;
}

pre {
background-color: #f8f8f8;
border: 1px solid #ccc;
font-size: 13px;
line-height: 19px;
overflow: auto;
padding: 6px 10px;
border-radius: 3px;
}

pre code, pre tt {
background-color: transparent;
border: none;
}

kbd {
-moz-border-bottom-colors: none;
-moz-border-left-colors: none;
-moz-border-right-colors: none;
-moz-border-top-colors: none;
background-color: #DDDDDD;
background-image: linear-gradient(#F1F1F1, #DDDDDD);
background-repeat: repeat-x;
border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD;
border-image: none;
border-radius: 2px 2px 2px 2px;
border-style: solid;
border-width: 1px;
font-family: "Helvetica Neue",Helvetica,Arial,sans-serif;
line-height: 10px;
padding: 1px 4px;
}

/* QUOTES
=============================================================================*/

blockquote {
border-left: 4px solid #DDD;
padding: 0 15px;
color: #777;
}

blockquote>:first-child {
margin-top: 0px;
}

blockquote>:last-child {
margin-bottom: 0px;
}

/* HORIZONTAL RULES
=============================================================================*/

hr {
clear: both;
margin: 15px 0;
height: 0px;
overflow: hidden;
border: none;
background: transparent;
border-bottom: 4px solid #ddd;
padding: 0;
}

/* IMAGES
=============================================================================*/

img {
max-width: 100%
}
-->

时间: 2024-08-02 21:45:15

简单学ES6 - class的相关文章

简单看看es6解构赋值

哎,我真的是太难了,今天就被这个解构赋值(也可以叫做析构,貌似析构是在c++中的,所以我这里叫做解构赋值吧)弄的我很烦,本来以为很容易的,结果还是弄了好久...就总结一下解构吧! 1.解构的基本使用 什么叫做解构呢?其实就是类似正则表达式的这么一个东西,就是用一个有规则的表达式去匹配一个对象,这个表达式中刚好有一些属性,只要是匹配到了的东西都会自动赋值给这些属性,然后这个属性我们就可以随便使用了,所以通用的写法应该是下面这个样子的(这里是对象类型的解构,对于数组类型的解构比较容易,不多说,自己查

简单学C——第四天

数组 在学数组之前,有必要把前面的知识复习一遍,当然我的复习,仅仅只是提一下,而对于你,则应该认真的看一下前面的知识点,不懂可以百度,哈哈. 前面我们大致学了 1.定义变量,2.数据的输入与输出,3.判断语句if...else if ...else  ,4.循环语句 while,do while,for 三种循环方式. 然而上面面讲的都是废话...下面开始讲数组. 数组是什么?数组是构造数据类型.很难懂吗?说直白一点,数组就是很多个相同的数据类型的元素聚集在一起之后的结果. 当然,使用数组的时候

简单学C——第五天

结构体 首先明确,结构体是一种构造的数据类型,是一种由多个数据类型如 int,char,double,数组或者结构体......组成的类型,现在告诉大家如何定义一个结构体.在定义int整型变量时,大家肯定都知道 int a;   即定义了一个int 型变量,系统会自动分配 存int这么大的空间,但是对于结构体而言,它是由许多个不确定的类型组成的,所以在定义它的时候需要指明它是由哪些数据类型组成的.定义格式有多种,此处只说一种较为简单的,定义格式如下. struct 名字 { 由哪些数据类型组成

简单总结es6箭头符号

1.es6箭头符号的几种写法 (1)没有参数 ()=>1*1 (2)一个参数 x=>x*x (3)两个参数以及多个参数 (x,y,z)=>x*y*z 2.箭头符号不会绑定this.arguments.super.new.target (1)arguments function foo() { setTimeout( () => { console.log("args:", arguments); },100); } foo( 2, 4, 6, 8 ); (2)t

python简单学------------python函数

如果在开发程序时,需要某块代码多次,但是为了提高编写的效率以及代码的重用,所以把具有独立功能的代码块组织为一个小模块,这就是函数 函数定义和调用 <1>定义函数 定义函数的格式如下: def 函数名(): 代码 demo: # 定义一个函数,能够完成打印信息的功能 def printInfo(): print '------------------------------------' print ' 人生苦短,我用Python' print '------------------------

龙猫Python简单学

机关算计基础知识 cpu 相当有大脑负责运算和处理问题 最快 内存 临时充储数据 快 硬盘 云久充储数据 慢 操作系统 为电脑上个个独立的基础设备提供桥梁让他们可以相互建立起链接 python的应用和历史 python2版本: 源码不统一,功能重复` 维护难度大 python3版本: 代码统一维护难度降低 python是个什么编程语言 ? 分类:编译型,解释型. ? 编译型;只翻译一次 ? 优点:运行速度快 ? 缺点:开发速度慢 代表:c,c++ ? 解释型:逐行翻译 ? 优点:开发速度快 ?

从零开始学ES6 -第一节(简介,块级作用域,let和const)

以下内容参考阮一峰老师的文章:http://es6.ruanyifeng.com/#docs/intro 一. ECMAScrpt 6简介 了解ES6转换器(bable,traceur) 申明变量的方法:var,let,const,function,import,class二. let和const命令 let命令 <!-- 声明的变量仅在块级作用域内有效 --> { let a=1; } a //报错 for(let i=0;i<10;i++){ } console.log(i) //报

重学ES6(一):数组及其新方法

数组的遍历 1.传统for循环 2.forEach方法,不支持break和continue const arr = [1, 2, 3, 4, 5] arr.forEach(function (item) { console.log(item) }) 3.every方法,可以做到 break 那样的效果,return false 等同于 break,return true 等同于 continue const arr = [1, 2, 3, 4, 5] // every 默认return fals

重学ES6(二):ES5和ES6中Class类的相同与不同

ES5和ES6中Class类的相同与不同 先说结论,简而言之ES5用function定义类,ES6用class定义类,class的本质是function,ES6中的类只是语法糖,它并没有改变ES5下类实现的本质. 类的定义 ES5 // ES5函数来描写类 // 声明类 let Animal = function (type) { this.type = type // 定义实例方法 this.drink = function () { console.log('drink') } } // 定