简单学ES6 - class

时间:2023-03-09 08:07:51
简单学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%
}
-->