ES6 特性

2020-05-18  本文已影响0人  33jubi

ES6

readable usable matainable

1.Arrow Function

function name(){};
函数是一等公民
解决:打底3行起步,可以不需要大括号

1.
const sum = (num1,num2)=>num1+num2;
2.
var getStudent = (name,age)=>({
    name:name,
    age:age,
});
3.箭头函数体内的 this对象,就是定义时所在的对象,而不是使用时所在的对象
var Person  =  function(name){
  this.name = name;
  this.getName=()=>this.name;
}
var alice = new Person();
alice.getName()//alice
//Person.prototype.getName=()=>this.name
//alice.getName()//undefined
//但如果上诉包在function里就会是alice

圆括号=>示意是一个返回函数,该用例就是返回一个object

2.Class

class Person{
  constructor(name){
    this.name = name;
  }
  sayHi(){
    console.log('my  name is '+this.name);
  }
  joinMeeting(meeting){
  //meeting.talks.push(this.sayHi);
    meeting.talks.push(()=>this.sayHi());//这样可以传递this指的值
  }
}
class Meeting{
  constructor(){
    this.talks = [];
  }
  start(){
    function talk(t){
      t();
    }
    this.talks.forEach(talk);
  }
  
}

var alice = new Person('Alice');
var  bob = new Person('Bob');

var standup = new Meeting();

alice.joinMeeting(standup);
bob.joinMeeting(standup);
standup.start();

3.let/const

let/const所声明的变量,只在其命令所在的代码块内有效
var有‘变量提升’现象,即变量可以在声明前使用,值为undefined
块级作用域
{}

4.template string模版字符串

嵌入变量
换行
... ${name}

5.destruring解构赋值

从数组和object取值,对变量进行赋值
const {body}=ctx.request;

6.浅拷贝

js在传参,除了object,都是拷贝值传递
object也是拷贝值

const foo =(a)=>{
  a={name:'Tifa'};
  return a;
  
};

const a={name:'Alice'};
const b=a;
b.name='Bob';
const c=foo(a);

console.log(a);//Bob=>浅拷贝
console.log(b);//Bob=>浅拷贝
console.log(c);//Tifa=>浅拷贝
const foo =(a)=>{
  a.name='Tifa';
  return a;
  
};

const a={name:'Alice'};
const b=a;
b.name='Bob';
const c=foo(a);

console.log(a);//Tifa
console.log(b);//Tifa
console.log(c);//Tifa

Immutable
在面向对象及函数编程中,不可变对象是一种对象,在被创造之后,它的 状态就不可以被改变

通过拷贝 实现

const getFruit=(arr)=>{
  const fruit = Array.from(arr).pop();//不会改变arr对象的值
  return fruit;
}
const getStudentWIthFormatScore = (student)=>{
  const newStudent = Object.assign({},student);
  newStudent.score=...
  return newStudent;
}

Immutable:

const obj = {name:'Alice'};
const obj1 = {...obj};//=Object.assign({},obj)

//[...newArrName]
//{...newObjectName}
上一篇下一篇

猜你喜欢

热点阅读