ES6 部分筆記
- 遞歸實(shí)現(xiàn)深層凍結(jié)
function myFreeze(obj){
Object.freeze(obj);
Object.keys(obj).forEach(function(key){
if(typeof obj[key] === 'object'){
myFreeze(obj[key]);
}
});
}
Object.keys(obj)
會(huì)返回當(dāng)前對(duì)象屬性所組成的一個(gè)數(shù)組。
- 使用箭頭函數(shù)作為事件的回調(diào)函數(shù)時(shí),函數(shù)中的this將指向window
使用箭頭函數(shù)定義對(duì)象中的方法時(shí)雨效,函數(shù)中的this將指向window;
不能夠使用箭頭函數(shù)作為構(gòu)造函數(shù)贾费;
不能定義原型下面的方法吕世;
arguments 是一個(gè)對(duì)應(yīng)于傳遞給函數(shù)的參數(shù)的類(lèi)數(shù)組對(duì)象。但是arguments在箭頭函數(shù)中不可以使用戴陡。
function func1(a, b, c) {
console.log(arguments[0]);
// expected output: 1
console.log(arguments[1]);
// expected output: 2
console.log(arguments[2]);
// expected output: 3
}
func1(1, 2, 3);
- 模版字符串
var roku = {name:'roku', hobby:'game'}
console.log(`你好塞绿,我叫${roku.name},我喜歡${roku.hobby}`)
//輸出:你好,我叫roku,我喜歡game
- 解構(gòu)賦值
const course = {
name:'es6',
price:500,
student: {
name: 'roku',
age:16
}
};
const{
name:courseName, //別名
price,
student:{
name, age
}
} = course;
console.log(courseName, price, name, age)
//output: es6 500 roku 16
解構(gòu)賦值使用場(chǎng)景:
1.函數(shù)參數(shù)
const sum = ([a, b, c]) => {
console.log(a+b+c)
};
sum([1, 2, 3])
//6
const foo = ({name, age, school='XX school'}) =>{
console.log(name, age, school)
};
foo({
name:'roku',
age:"20",
});
//roku 20 XX school
2.函數(shù)返回值
const foo = () =>{
return{
name:'張三',
age: 20
}
};
const {name,age} = foo();
console.log(name, age);
//張三 20
3.變量互換
a = 1,b = 2;
[b,a] = [a,b];
console.log(a,b);
//2 1
4.JSON應(yīng)用
const json = '{"name":"es", "price":"500"}';
const{name, price} = JSON.parse(json);
console.log(name, price);
//es 500
5.Ajax請(qǐng)求應(yīng)用
請(qǐng)求JSON文件數(shù)據(jù),引入axios CDN庫(kù)
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.1.0/axios.amd.js"></script>
axios.get
方法獲取JSON數(shù)據(jù)文件恤批。
//JSON文件內(nèi)容:
{
"name": "es6",
"type": "前端"
}
//js文件頁(yè)面內(nèi)容
axios.get('./data.json').then(({data:{name, type}})=>{
console.log(name, type);
});
// es6 前端
- 瀏覽器兼容問(wèn)題
ES6=>BABEL(轉(zhuǎn)化)=>ES5=>瀏覽器