1
0
mirror of https://github.com/ruanyf/es6tutorial.git synced 2025-05-24 18:32:22 +00:00

edit class/module

This commit is contained in:
ruanyf 2014-05-04 01:38:58 +08:00
parent bfcfe3cbfa
commit 291c9455be
2 changed files with 62 additions and 3 deletions

View File

@ -50,6 +50,8 @@ class ColorPoint extends Point {
## Module的基本用法
**1export和import**
ES6实现了模块功能试图解决JavaScript代码的依赖和部署上的问题。模块功能有两个关键字export和import。export用于用户自定义模块规定对外接口import用于输入其他模块提供的功能同时创造命名空间namespace防止函数名冲突。
ES6允许将独立的JS文件作为模块也就是说允许一个JavaScript脚本文件调用另一个脚本文件。最简单的模块就是一个JS文件里面使用export关键字输出变量。
@ -77,7 +79,17 @@ function setHeader(element) {
上面代码中import关键字接受一个对象用大括号表示里面指定要从其他模块导入的变量。大括号里面的变量名必须与被导入模块对外接口的名称相同。
export关键字除了输出变量还可以输出方法。下面是一个circle.js文件它输出两个方法。
如果想为输入的属性或方法重新取一个名字import语言要写成下面这样。
```javascript
import { someMethod, another as newName } from './exporter';
```
**2模块的整体加载**
export关键字除了输出变量还可以输出方法或类class。下面是一个circle.js文件它输出两个方法。
```javascript
@ -120,6 +132,44 @@ console.log("圆周长:" + circle.circumference(14));
module关键字后面跟一个变量表示导入的模块定义在该变量上。
**3export default语句**
如果不想为某个属性或方法指定输入的名称可以使用export default语句。
```javascript
// export-default.js
export default function foo() {
console.log('foo');
}
```
上面代码中的foo方法就被称为该模块的默认方法。
在其他模块导入该模块时import语句可以为默认方法指定任意名字。
```javascript
// import-default.js
import customName from './export-default';
customName(); // 'foo'
```
显然,一个模块只能有一个默认方法。
如果要输出默认属性,只需将值跟在`export default之后`即可。
```javascript
export default 42;
```
## 模块的继承
模块之间也可以继承。
@ -138,7 +188,15 @@ export default function(x) {
```
上面代码中的“export *”表示导入circle模块的所有属性和方法。export default命令表示定义模块的默认方法。
上面代码中的“export *”表示输出circle模块的所有属性和方法export default命令定义模块的默认方法。
这时可以为circle中的属性或方法改名后再输出。
```javascript
export { area as circleArea } from 'circle';
```
加载上面模块的写法如下。

View File

@ -15,7 +15,7 @@
- Justin Drake, [ECMAScript 6 in Node.JS](https://github.com/JustinDrake/node-es6-examples)
- Ryan Dao, [Summary of ECMAScript 6 major features](http://ryandao.net/portal/content/summary-ecmascript-6-major-features)
- Luke Hoban, [ES6 features](https://github.com/lukehoban/es6features)
- Traceur-compiler, [Language Features](https://github.com/google/traceur-compiler/wiki/LanguageFeatures): Traceur编译列出的一些ES6例子
- Traceur-compiler, [Language Features](https://github.com/google/traceur-compiler/wiki/LanguageFeatures): Traceur文档列出的一些ES6例子
## 语法点
@ -42,3 +42,4 @@
- Google, [traceur-compiler](https://github.com/google/traceur-compiler): Traceur编译器
- Casper Beyer, [ECMAScript 6 Features and Tools](http://caspervonb.github.io/2014/03/05/ecmascript6-features-and-tools.html)
- Stoyan Stefanov, [Writing ES6 today with jstransform](http://www.phpied.com/writing-es6-today-with-jstransform/)
- ES6 Module Loader, [ES6 Module Loader Polyfill](https://github.com/ModuleLoader/es6-module-loader): 在浏览器和node.js加载ES6模块的一个库文档里对ES6模块有详细解释