1. const、let關(guān)鍵字
在javascript中,變量默認(rèn)是全局性的,只存在函數(shù)級作用域,聲明函數(shù)曾經(jīng)是創(chuàng)造作用域的唯一方法。為了解決塊級作用域的問題,ES6中提出了let關(guān)鍵字。
// console.log(a); a is not defined
let a = 'john';
console.log(a);
同時還引入的概念是const,用來定義一個常亮,一旦定義以后不可以修改,不過如果是引用類型的,那么可以改變它的屬性。
// console.log(a); a is not defined
const a = 'john';
// a = 'lucy'; Assignment to constant variable
// a is read-only
console.log(a);
const a = { name: 'john' };
a.name = 'lucy';
// 可以正常運行
console.log(a);
2. 函數(shù)
- 箭頭函數(shù)
箭頭函數(shù)是一種更簡單的函數(shù)聲明方式,可以把它看做是一種語法糖,箭頭函數(shù)是永遠(yuǎn)匿名的。
let add = (a,b) => {return a + b};
// 當(dāng)后面是表達(dá)式(expression)的時候,還可以簡寫為
let add = (a,b) => a + b;
// 等同于
let add = function (a,b) {
return a + b;
}
// 在回調(diào)函數(shù)中的應(yīng)用
let numbers = [1, 2, 3];
let doubleNumbers = numbers.map((number) => number * 2);
console.log(doubleNumbers);
- this在箭頭函數(shù)中的使用
let age = 2;
let john = {
age: 1,
grow: function () {
setTimeout(function(){}, 1000);
}
};
john.grow();
// 此處結(jié)果是NaN 原因是let聲明的變量是塊級作用域,不是全局變量
var age = 2;
let john = {
age: 1,
grow: function(){
setTimeout(function(){
console.log(++this.age)
},100);
}
}
john.grow();
// 此處結(jié)果是3
在對象方法的嵌套函數(shù)中,this會指向global對象。一般為了解決這種問題,會采用一些hack來解決它。
let john = {
age: 1,
grow: function(){
const self = this;
setTimeout(function(){
console.log(++self.age);
},100)
}
}
// 或者
let john = {
age: 1,
grow: function(){
setTimeout(function(){
console.log(this.age)
}.bind(this),100)
}
}
使用箭頭函數(shù)就可以輕松解決這個問題
let kitty = {
age: 1,
grow: function(){
setTimeout(()=>{console.log(this.age)},100);
}
}
- 函數(shù)默認(rèn)參數(shù)