美文网首页
ES6学习笔记

ES6学习笔记

作者: 尚无花名 | 来源:发表于2019-05-12 05:17 被阅读0次

Arrow function

JS里面用这种
JS : function myFun(param){ }
ES6里面用
const myFunc = () => { }
这样可以避免this作用域的问题

只有一个的话不用括号, 有两个的话才用括号, 空的话也要用括号,空的括号。

const printMyName = (name, bday) => {
  console.log(name + ", " +  bday);
}
const multiply = number => {
 return number * 2
}
const multiply = number => number * 2;
const multiply2 = (num1, num2) => num1 * num2;

Export & Import

const person = {
  name:'Max'
}
export default person

default keyword,

import {smith} from './utility.js'
import { smith as Smth} from './utility.js' //alias
import * as bundled from './utility.js' // bundled.props

Class

Blue print for object
can have both property and method
new : constructor
extend : 继承

class Human{
  constructor() {
    this.gender = 'male';
  }
  printGender() {
    console.log(this.gender);
  }
}

class Person extends Human{
  constructor(){
    super();//继承时一定要有super
    this.name = 'Alvin';
  }
  printMyName(){
    console.log(this.name);
  }
}
const person = new Person();
person.printMyName();
person.printGender();

不需要写在constructor里了
ES6 是这么写的

class Human{
  gender = 'male';
  printGender = () => {
    console.log(this.gender);
  }
}

class Person extends Human{
  name = 'Max';
  gender = 'female';
  printMyName = () => {
    console.log(this.name);
  }
}
const person = new Person();
person.printMyName();
person.printGender();

Spread & Rest Operators
...
Spread split up array element Or Object properties

const array2 = [...array1, 1, 2]
const obj2 = {...obj1, newProp:6}

Rest

function sortArgs(...args) {
  return args.sort();
}

Destructuring

[a, b] = ['Hello', 'Alvin']
{name} = {name: 'Alvin', age: 28}

Reference and primitive types

Similar as Java
对于object, 是copy reference,
但这种情况,就是copy reference了

const person = {
  name: 'Max'
};
const person2 = {
  ...person
};
person.name = 'Matt';
console.log(secondPerson) 
因为这是一个object, 所以 

forEach

dwarves.forEach(function(element, index, array) {
  console.log(element);
});

map & filter

map transform to same length array
filter transform to smaller array

const products = [
  {'name' : 'hammer', 'price' : 10},
 {'name' : 'chisel', 'price' : 4.9}
]
var names = products.map(p => p.name);
var result = products.map(p => (p.price > 5));
var sale_products = products.map( p => {
  y = {},
  y.name = p.name,
  y.on_sale = (p.price > 4);
  return y;
});
var expensive = x => x['price'] > 5;
var expensive_products = products.filter(expensive);

reduce

var orders = [
  { amount : 250},
  { amount : 400},
  {amount : 100}
]
var totalAmount = orders.reduce(function(sum, order) {
  return sum + order.amount;
}, 0);

相关文章

网友评论

      本文标题:ES6学习笔记

      本文链接:https://www.haomeiwen.com/subject/ixofaqtx.html