@lizlalala
2016-09-23T01:06:40.000000Z
字数 2263
阅读 1553
es6
箭头函数、模板字符串、promise、generator(iter.next去执行yield内容)、class、module
for(let i=0;i<6;i++){a[i] = function(){console.log(i);}}//es5的实现应该是介样的for(var i=0;i<6;i++){(function(i){a[i] = function(){console.log(i);}})(i);}
2,用模板变量代替字符串拼接
`${x}+$(y)` == x+"+"+y
模板字面量可以横跨多行。
空格和换行都会保留
3,函数的默认参数应该在最右边,实参与形参从左开始匹配
4,class
//es5function Point(x,y){this.x = x;this.y = y;}Point.prototype.toString = function () {return '(' + this.x + ', ' + this.y + ')';}//es6class Point{constructor(x,y){this.x = x;this.y = y;}toString(){return '(' + this.x + ', ' + this.y + ')';}}
注意点:
私有方法:
把私有方法都放外部,class内部只存暴露出去的公有方法,比如
class Widget {foo (baz) {bar.call(this, baz);}// ...}function bar(baz){...}
用symbol处理私有方法和属性的名称
const privateFun = Symbol('bar');const privateParam = Symbol('bar');class test1{//私有方法[bar](param){//私有属性this[privateParam] = ...}fun1(){this[bar]("实参");}}
5, 继承
通过extends关键字,继承了父类的所有属性和方法。等于复制了一个Point类
class Rectangle extends Shape {constructor (id, x, y, width, height) {super(id, x, y) //父类构造函数,必须调用,用来新建父类的this实例,同时复制一份作为自己的this.width = widththis.height = height}}//es5function Rectangle(id, x, y, width, height) {Shape.call(this, id, x, y)//复制一份父类shape的属性id,x,y,用自己的值进行初始化this.width = widththis.height = height}Rectangle.prototype = Object.create(Shape.prototype)//深复制父类的原型,然后改变原型的指向,使得子类自己保持一份原型Rectangle.prototype.constructor = Rectangle
6, 静态属性方法
class Foo {static classMethod() {return 'hello';}}class Bar extends Foo {}Bar.classMethod(); // 'hello'
class Foo {}Foo.prop = 1;Foo.prop // 1
class MyClass {myProp = 42;constructor() {console.log(this.myProp); // 42//以前的写法:this.myProp = ...}}//或者更复杂的是class ReactCounter extends React.Component {newProps = {count:3;};state; //constructor里面已经定义的实例属性constructor(props) {super(props);this.state = {count: 0};}}
es7中静态属性提案,将静态属性也像实例属性一样放进来
class MyClass {static myStaticProp = 42;constructor() {console.log(MyClass.myProp); // 42}}
var firstName = 'mei';var lastName = 'qingguang';var year = 1988;//exportexport {firstName, lastName, year};//importimport {firstName, lastName, year} from "./module1.js"console.log(firstName);或者import * as Module1 from "./module1.js"console.log(Module1.firstName)//整体输出的话//test1.jsexport default function(){...}import yourModuleName from "test1.js"yourModuleName() //函数执行
