閉包閉包是Javascript中的一項重要技術(shù),內(nèi)部函數(shù)始終可以訪問其外部函數(shù)的變量和參數(shù),即使在外部函數(shù)返回后也是如此。我們使用閉包來保護(hù)我們不想向外部范圍公開的數(shù)據(jù)。 //<button onclick=”increaseCounter()”>Increase Counter</button>//1. 全局變量,變量會被意外修改let counter = 0;function increaseCounter() { counter++;}//2. 局部變量,每次調(diào)用都重置為0function increaseCounter() { let counter = 0; counter++;}//3. 閉包函數(shù),符合要求const increaseCounter = (function() { let counter = 0; return function() { counter = counter + 1; console.log(counter); };})();函數(shù)綁定在上下文丟失時,this將無法被確定,可以通過函數(shù)綁定解決。 使用命名空間使用命名空間可以防止代碼沖突。 // 1. move、jump函數(shù)在animal命名空間下,需要通過animal.move()來調(diào)用let animal = { move: () => { console.log('Move!’); }, jump: () => { consle.log('Jump!’); }};// 2. 真實項目中,可能會按如下方式使用命名空間if (typeof APP === 'undefined') { APP = {}; APP.ANIMAL = {};}APP.ANIMAL.move = () => { console.log('Move’);};APP.ANIMAL.jump = () => { console.log('Jump’);};APP.ANIMAL.move(); // MoveAPP.ANIMAL.jump(); // Jump判斷屬性是否存在使用in關(guān)鍵字可以判斷對象中是否存在某個屬性。 解構(gòu)賦值利用解構(gòu)賦值表達(dá)式,可以將屬性、值從對象、數(shù)組中取出,賦值給其它變量,非常方便。 const { address: addressLine } = { address: '長安街20號', postcode: '518118' };console.warn(addressLine); // 長安街20號const [first, second] = [1, 2, 3, 4]console.warn(first, second) // 1 2//動態(tài)解構(gòu)const extractKey = 'postcode'const { [extractKey]: youbian } = { address: '長安街20號', postcode: '518118' };console.log(youbian) //518118遍歷對象屬性使用Object.entries可以遍歷對象的屬性和值。 過濾數(shù)組利用數(shù)組的filter、some對數(shù)組進(jìn)行篩選。 const fruits = ['apple', null, 'mongo', undefined, '']const filted = fruits.filter(Boolean)console.debug(filted) //(2) ['apple', 'mongo']const any = fruits.some(Boolean)console.log(any) //true消除重復(fù)值判斷是否數(shù)組利用Array.isArray,而不是typeof判斷。 const fruits = ['apple', null, 'mongo', 'apple', '']console.debug(typeof fruits) //objectconsole.error(Array.isArray(fruits)) //true轉(zhuǎn)換數(shù)字和字符串轉(zhuǎn)換為boolean利用!!運算符可以將其它類型轉(zhuǎn)換為Boolean類型。 console.log(!!null, typeof(!!null)) //false, booleanconsole.log(!!'', typeof(!!'')) //false, booleanconsole.log(!!undefined, typeof(!!undefined)) //false, booleanconsole.log(!!null, typeof(!!null)) //false, booleanconsole.log(!!true, typeof(!!true)) //true, booleanconsole.log(!!false, typeof(!!false)) //false, booleanconsole.log(!!{id:'', name:''}, typeof(!!{id:'', name:''})) //true, boolean可選鏈可選鏈 ?. 是一種訪問嵌套對象屬性的安全的方式,可避免在對象或?qū)傩圆豢捎脮r拋出異常。由于JavaScript不是類型化語言,該特性還是很有用。 合并運算符合并運算符的寫法為兩個問號 ??,對于該運算符連接的兩個參數(shù),如果第一個參數(shù)不是 null,也不是undefined,則返回第一個參數(shù),否則返回第二個參數(shù)。 const contactInfos = { address: '長安街20號' };console.warn(contactInfos.user?.phoneNumber ?? '') // ''const contactInfos = { address: '長安街20號', addressNumber: 0 };console.warn(contactInfos.addressNumber || undefined) // undefinedconsole.warn(contactInfos.addressNumber ?? undefined) // 0有條件地添加屬性使用...擴(kuò)展語法,可以僅當(dāng)某個條件成立時,才為對象添加某個屬性。 異步調(diào)用異常捕獲以下寫法讓處理異步調(diào)用異常的代碼變得更為簡潔。 const results = await getPosts().catch((err) => { return { type: 'error', message: err.message }});console.warn(results) // { type: 'error', message: 'cannot get posts from this endpoint' }弱引用MapWeakmap不同于Map,它的鍵必須是引用對象,不能是基礎(chǔ)類型,如果沒有對該鍵對象引用時,該對象將被從Map和內(nèi)存中移除。 反射Reflect是一個全局對象,它為元編程提供了一些有用的靜態(tài)方法。 const person = { name: 'Bob', [Symbol('email')]: 'bob@evil.com' };Reflect.get(person, 'name'); // = BobReflect.has(person, 'email'); // = trueReflect.has(person, 'phone'); // = falseReflect.getPrototypeOf(person); // = { constructor ... }Reflect.getOwnPropertyDescriptor( person, 'name'); // = { value: 'Bob', writable: true, enumerable: true, configurable: true }Reflect.ownKeys(person); // name, Symbol(email)Reflect.defineProperty(person, 'phone', { writable: true });Reflect.has(person, 'phone'); // = trueReflect.set(person, 'phone', '123456789');Reflect.deleteProperty(person, 'phone');Reflect.has(person, 'phone'); // = false柯里化柯里化(Currying)是一種關(guān)于函數(shù)的高階技術(shù),它是指將一個函數(shù)從可調(diào)用的 f(a, b, c) 轉(zhuǎn)換為可調(diào)用的 f(a)(b)(c)??吕锘粫{(diào)用函數(shù),它只是對函數(shù)進(jìn)行轉(zhuǎn)換。 組合組合是一種技術(shù),其中一個函數(shù)的結(jié)果被傳遞到下一個函數(shù),該函數(shù)被傳遞到下一個函數(shù),依此類推......直到執(zhí)行最終函數(shù)并計算出一些結(jié)果。函數(shù)組合可以由任意數(shù)量的函數(shù)組成。 //f 和 g 都是函數(shù),x 是在它們之間通過“管道”傳輸?shù)闹祐ar compose = function(f,g) { return function(x) { return f(g(x)); };};var toUpperCase = function(x) { return x.toUpperCase(); };var exclaim = function(x) { return x + '!'; };var shout = compose(exclaim, toUpperCase);shout('send in the clowns'); //=> 'SEND IN THE CLOWNS!'
|
|
|