二、es6语法学习:
这几天把es6的语法过了一遍了,把一些常用的语法做了些小练习,算是基本入门了,我主要看这个网站进行学习的http://es6.ruanyifeng.com/。
对项目添加了一些简单的配置,为了方便可查看效果。
路由配置:
1 import letTest from ‘./es6/let.js‘; 2 import classTest from ‘./es6/class.js‘; 3 import moduleFunc from ‘./es6/moduleAction.js‘; 4 import promise from ‘./es6/promise.js‘; 5 6 export default { 7 "let": { "func": letTest }, 8 "class": { "func": classTest }, 9 ‘module‘: { ‘func‘: moduleFunc }, 10 ‘promise‘: { ‘func‘: promise } 11 }
入口文件:
1 import person from ‘./es6/person.js‘; 2 import route from ‘./route.js‘ 3 4 let hash = window.location.hash; 5 let strHash = hash.substr(1, hash.length); 6 if (strHash == ‘‘) { 7 let p = new person(‘webpack‘, ‘hello‘); 8 document.write(p.say()); 9 } else { 10 route[strHash][‘func‘](); 11 }
http://localhost:7777/#let 这样既可查看运行例子,以锚点作为为例子的名称。
1、let 命令:
1 export default function() { 2 let name = ‘zach‘; 3 4 while (true) { 5 let name = ‘obama‘; 6 document.write(name);//obama 7 document.write(‘<br />‘) 8 break; 9 } 10 11 document.write(name);//zach 12 }
2、class
1 class Animal { 2 constructor() { 3 this.type = "animal"; 4 } 5 6 says(say) { 7 say = say || ‘hello‘; 8 document.write(`${this.type} says ${say} <br/>`); 9 } 10 } 11 12 class Cat extends Animal { 13 constructor() { 14 super(); //访问父类的属于属性与方法 15 this.type = "cat"; 16 } 17 } 18 19 export default function() { 20 let animal = new Animal(); 21 animal.says(); 22 23 let cat = new Cat(); 24 cat.says(‘hi‘); 25 }
2、module 加载
1 export let counter = 3; 2 export function inCounter() { 3 counter++; 4 }
引用,执行方法
1 import { counter, inCounter } from ‘./module.js‘; 2 3 export default () => { 4 let html = `<div>${counter}</div>`; 5 document.write(html); 6 inCounter(); 7 html = `<div>${counter}</div>`; 8 document.write(html); 9 }
3、promise 异步方法
function actionProise() { let promise = new Promise(function(reslove, reject) { try { let box = document.createElement(‘div‘); document.body.appendChild(box); let i = 0; let t = setInterval(() => { i++; box.innerHTML = i; if (i > 99) { clearInterval(t); reslove(i); //异步执行成功 } }, 500); } catch (e) { reject(e.message); //异步执行失败 } }); return promise; } export default () => { document.write(‘<div>异步执行开始</div>‘); actionProise().then((value) => { document.write(‘<div>异步执行成功</div>‘); }, (error) => { document.write(‘<div>异步执行失败</div>‘); }); }
以上就是我的es6方法的,学习了,详细运行下例子就知道了。上面的列子也包括了一些es6的语法糖的写法。
源码地址:https://github.com/codeyoyo/Full-stack-development.git
时间: 2024-10-24 09:58:41