ES6入门
1.利用gulp+babel转es6 http://www.cnblogs.com/sanxiaoshan/p/6850342.html
2.目录结构
3.index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.js"></script>
</head>
<body>
<div style="margin-top: 20px">
<input type="button" class="button" value="按钮1">
<input type="button" class="button" value="按钮2">
<input type="button" class="button" value="按钮3">
<input type="button" class="button" value="按钮4">
<input type="button" class="button" value="按钮5">
</div>
<div id="result"></div>
<script src="es6/index.js" ></script>
</body>
</html>
4.gulpfile.js
var gulp = require('gulp');
var babel = require('gulp-babel');
gulp.task('default', function () {
return gulp.src('es6/*.js')
.pipe(babel({
presets:['es2015']
}))
.pipe(gulp.dest('build'))
console.log('ok');
});
5.index.js
//let为JavaScript新增了块级作用域。用它所声明的变量,只在let命令所在的代码块内有效
//----------------------------es5---------------------------------
var name_es5 = 'zach'
while (true) {
var name_es5 = 'obama'
console.log(name_es5) //obama
break
}
console.log(name_es5) //obama
//----------------------------es5---------------------------------
//----------------------------es6---------------------------------
let name_es6 = 'zach'
while (true) {
let name_es6 = 'obama'
console.log(name_es6) //obama
break
}
console.log(name_es6) //zach
//----------------------------es6---------------------------------
//----------------------------es5---------------------------------
var add_the_handlers_new = function (nodes) {
var helper = function (i) {
return function (e) {
alert(i);
}
}
var i;
for (i = 0; i < nodes.length; i++) {
nodes[i].onclick = helper(i + 1);
}
};
add_the_handlers_new($('.button'));
//----------------------------es5---------------------------------
//----------------------------es6---------------------------------
var add_the_handlers_new_es6 = function (nodes) {
for (let i = 0; i < nodes.length; i++) {
$(nodes[i]).click(function () {
console.log(i);
});
}
};
add_the_handlers_new_es6($('.button'));
//----------------------------es6---------------------------------
//const也用来声明变量,但是声明的是常量。一旦声明,常量的值就不能改变。
//const有一个很好的应用场景,就是当我们引用第三方库的时声明的变量,用const来声明可以避免未来不小心重命名而导致出现bug
const PI = Math.PI
//PI = 23 //Module build failed: SyntaxError: /es6/app.js: "PI" is read-only
//const monent = require('moment')
//class, extends, super
//class定义了一个“类”,constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实例对象可以共享的
//extends关键字实现继承
//super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子
//类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
class Animal {
constructor(){
this.type = 'animal'
}
says(say){
console.log(this.type + ' says ' + say)
}
}
let animal = new Animal()
animal.says('hello') //animal says hello
class Cat extends Animal {
constructor(){
super()
this.type = 'cat'
}
}
let cat = new Cat()
cat.says('hello') //cat says hello
//当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
//并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。
class Animal2 {
constructor(){
this.type = 'animal'
}
says(say){
setTimeout( () => {
console.log(this.type + ' says ' + say)
}, 1000)
}
}
var animal2 = new Animal2()
animal2.says('hi') //animal says hi
var basket = {
count : '10',
onSale: '6'
};
//template string
//这个东西可以用在我们要插入大段的html内容到文档中。
$("#result").append(`
There are <b>${basket.count}</b> items
in your basket, <em>${basket.onSale}</em>
are on sale!
`);
//从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。
let mycat = 'ken'
let dog = 'lili'
let zoo = {mycat, dog}
console.log(zoo) //Object {mycat: "ken", dog: "lili"}
let mydog = {type: 'animal', many: 2}
let { type, many} = mydog
console.log(type, many) //animal 2
//default很简单,意思就是默认值。大家可以看下面的例子,调用animal()方法时忘了传参数,传统的做法就是加上这一句type = type || 'cat' 来指定默认值
function myanimal(type = 'cat'){
console.log(type)
}
myanimal()
//rest语法也很简单,直接看例子
function animals(...types){
console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]
6.编译后的index.js
'use strict';
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
//let为JavaScript新增了块级作用域。用它所声明的变量,只在let命令所在的代码块内有效
//----------------------------es5---------------------------------
var name_es5 = 'zach';
while (true) {
var name_es5 = 'obama';
console.log(name_es5); //obama
break;
}
console.log(name_es5); //obama
//----------------------------es5---------------------------------
//----------------------------es6---------------------------------
var name_es6 = 'zach';
while (true) {
var _name_es = 'obama';
console.log(_name_es); //obama
break;
}
console.log(name_es6); //zach
//----------------------------es6---------------------------------
//----------------------------es5---------------------------------
var add_the_handlers_new = function add_the_handlers_new(nodes) {
var helper = function helper(i) {
return function (e) {
alert(i);
};
};
var i;
for (i = 0; i < nodes.length; i++) {
nodes[i].onclick = helper(i + 1);
}
};
add_the_handlers_new($('.button'));
//----------------------------es5---------------------------------
//----------------------------es6---------------------------------
var add_the_handlers_new_es6 = function add_the_handlers_new_es6(nodes) {
var _loop = function _loop(i) {
$(nodes[i]).click(function () {
console.log(i);
});
};
for (var i = 0; i < nodes.length; i++) {
_loop(i);
}
};
add_the_handlers_new_es6($('.button'));
//----------------------------es6---------------------------------
//const也用来声明变量,但是声明的是常量。一旦声明,常量的值就不能改变。
//const有一个很好的应用场景,就是当我们引用第三方库的时声明的变量,用const来声明可以避免未来不小心重命名而导致出现bug
var PI = Math.PI;
//PI = 23 //Module build failed: SyntaxError: /es6/app.js: "PI" is read-only
//const monent = require('moment')
//class, extends, super
//class定义了一个“类”,constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实例对象可以共享的
//extends关键字实现继承
//super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子
//类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
var Animal = function () {
function Animal() {
_classCallCheck(this, Animal);
this.type = 'animal';
}
_createClass(Animal, [{
key: 'says',
value: function says(say) {
console.log(this.type + ' says ' + say);
}
}]);
return Animal;
}();
var animal = new Animal();
animal.says('hello'); //animal says hello
var Cat = function (_Animal) {
_inherits(Cat, _Animal);
function Cat() {
_classCallCheck(this, Cat);
var _this = _possibleConstructorReturn(this, (Cat.__proto__ || Object.getPrototypeOf(Cat)).call(this));
_this.type = 'cat';
return _this;
}
return Cat;
}(Animal);
var cat = new Cat();
cat.says('hello'); //cat says hello
//当我们使用箭头函数时,函数体内的this对象,就是定义时所在的对象,而不是使用时所在的对象。
//并不是因为箭头函数内部有绑定this的机制,实际原因是箭头函数根本没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。
var Animal2 = function () {
function Animal2() {
_classCallCheck(this, Animal2);
this.type = 'animal';
}
_createClass(Animal2, [{
key: 'says',
value: function says(say) {
var _this2 = this;
setTimeout(function () {
console.log(_this2.type + ' says ' + say);
}, 1000);
}
}]);
return Animal2;
}();
var animal2 = new Animal2();
animal2.says('hi'); //animal says hi
var basket = {
count: '10',
onSale: '6'
};
//template string
//这个东西可以用在我们要插入大段的html内容到文档中。
$("#result").append('\n There are <b>' + basket.count + '</b> items\n in your basket, <em>' + basket.onSale + '</em>\n are on sale!\n');
//从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring)。
var mycat = 'ken';
var dog = 'lili';
var zoo = { mycat: mycat, dog: dog };
console.log(zoo); //Object {mycat: "ken", dog: "lili"}
var mydog = { type: 'animal', many: 2 };
var type = mydog.type,
many = mydog.many;
console.log(type, many); //animal 2
//default很简单,意思就是默认值。大家可以看下面的例子,调用animal()方法时忘了传参数,传统的做法就是加上这一句type = type || 'cat' 来指定默认值
function myanimal() {
var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'cat';
console.log(type);
}
myanimal();
//rest语法也很简单,直接看例子
function animals() {
for (var _len = arguments.length, types = Array(_len), _key = 0; _key < _len; _key++) {
types[_key] = arguments[_key];
}
console.log(types);
}
animals('cat', 'dog', 'fish'); //["cat", "dog", "fish"]
7.
8.参考链接:https://segmentfault.com/a/1190000004365693