ES6
readable usable matainable
1.Arrow Function
function name(){};
函數(shù)是一等公民
解決:打底3行起步,可以不需要大括號(hào)
1.
const sum = (num1,num2)=>num1+num2;
2.
var getStudent = (name,age)=>({
name:name,
age:age,
});
3.箭頭函數(shù)體內(nèi)的 this對(duì)象塑崖,就是定義時(shí)所在的對(duì)象侵俗,而不是使用時(shí)所在的對(duì)象
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里就會(huì)是alice
圓括號(hào)=>示意是一個(gè)返回函數(shù),該用例就是返回一個(gè)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所聲明的變量,只在其命令所在的代碼塊內(nèi)有效
var有‘變量提升’現(xiàn)象泽裳,即變量可以在聲明前使用瞒斩,值為undefined
塊級(jí)作用域
{}
4.template string模版字符串
嵌入變量
換行
... ${name}
5.destruring解構(gòu)賦值
從數(shù)組和object取值,對(duì)變量進(jìn)行賦值
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
在面向?qū)ο蠹昂瘮?shù)編程中,不可變對(duì)象是一種對(duì)象瀑梗,在被創(chuàng)造之后烹笔,它的 狀態(tài)就不可以被改變
通過拷貝 實(shí)現(xiàn)
const getFruit=(arr)=>{
const fruit = Array.from(arr).pop();//不會(huì)改變arr對(duì)象的值
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}