[关闭]
@lizlalala 2016-09-23T01:06:40.000000Z 字数 2263 阅读 1200

es6学习(一)

es6


概览

箭头函数、模板字符串、promise、generator(iter.next去执行yield内容)、class、module

杂记

  1. 作用域,用代码块+let 替代IIFE,特别是let可以处理闭包的问题
    补充见另一篇笔记
  1. for(let i=0;i<6;i++){
  2. a[i] = function(){
  3. console.log(i);
  4. }
  5. }
  6. //es5的实现应该是介样的
  7. for(var i=0;i<6;i++){
  8. (function(i){
  9. a[i] = function(){
  10. console.log(i);
  11. }
  12. })(i);
  13. }

2,用模板变量代替字符串拼接

  1. `${x}+$(y)` == x+"+"+y

模板字面量可以横跨多行。

空格和换行都会保留

3,函数的默认参数应该在最右边,实参与形参从左开始匹配

4,class

  1. //es5
  2. function Point(x,y){
  3. this.x = x;
  4. this.y = y;
  5. }
  6. Point.prototype.toString = function () {
  7. return '(' + this.x + ', ' + this.y + ')';
  8. }
  9. //es6
  10. class Point{
  11. constructor(x,y){
  12. this.x = x;
  13. this.y = y;
  14. }
  15. toString(){
  16. return '(' + this.x + ', ' + this.y + ')';
  17. }
  18. }

注意点:


5, 继承
通过extends关键字,继承了父类的所有属性和方法。等于复制了一个Point类

  1. class Rectangle extends Shape {
  2. constructor (id, x, y, width, height) {
  3. super(id, x, y) //父类构造函数,必须调用,用来新建父类的this实例,同时复制一份作为自己的
  4. this.width = width
  5. this.height = height
  6. }
  7. }
  8. //es5
  9. function Rectangle(id, x, y, width, height) {
  10. Shape.call(this, id, x, y)//复制一份父类shape的属性id,x,y,用自己的值进行初始化
  11. this.width = width
  12. this.height = height
  13. }
  14. Rectangle.prototype = Object.create(Shape.prototype)//深复制父类的原型,然后改变原型的指向,使得子类自己保持一份原型
  15. Rectangle.prototype.constructor = Rectangle

6, 静态属性方法

  1. class Foo {
  2. static classMethod() {
  3. return 'hello';
  4. }
  5. }
  6. class Bar extends Foo {
  7. }
  8. Bar.classMethod(); // 'hello'
  1. class Foo {
  2. }
  3. Foo.prop = 1;
  4. Foo.prop // 1
  1. class MyClass {
  2. myProp = 42;
  3. constructor() {
  4. console.log(this.myProp); // 42
  5. //以前的写法:this.myProp = ...
  6. }
  7. }
  8. //或者更复杂的是
  9. class ReactCounter extends React.Component {
  10. newProps = {
  11. count:3;
  12. };
  13. state; //constructor里面已经定义的实例属性
  14. constructor(props) {
  15. super(props);
  16. this.state = {
  17. count: 0
  18. };
  19. }
  20. }

es7中静态属性提案,将静态属性也像实例属性一样放进来

  1. class MyClass {
  2. static myStaticProp = 42;
  3. constructor() {
  4. console.log(MyClass.myProp); // 42
  5. }
  6. }

  1. Module模块化
  1. var firstName = 'mei';
  2. var lastName = 'qingguang';
  3. var year = 1988;
  4. //export
  5. export {firstName, lastName, year};
  6. //import
  7. import {firstName, lastName, year} from "./module1.js"
  8. console.log(firstName);
  9. 或者
  10. import * as Module1 from "./module1.js"
  11. console.log(Module1.firstName)
  12. //整体输出的话
  13. //test1.js
  14. export default function(){
  15. ...
  16. }
  17. import yourModuleName from "test1.js"
  18. yourModuleName() //函数执行
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注