javascript
JavaScript的几个概念简单理解(深入解释见You Don't know JavaScript这本书)
ES201X是JavaScript的一個(gè)版本。
?
ES2015新的feature
- let, const
- Scope, 塊作用域
- Hoisting
- Closures
- DataStructures: Objects and Arrays
- this
?
?
let, const, Block Scope
?
新的聲明類型let, const,配合Block Scope。(if, forEach,)
之前:
var,? Global scope和function scope。
之后:
let, const , 這2個(gè)類型聲明用在Block Scope內(nèi)。
?
聲明一次還是多次?
let, const只能聲明一次。但var聲明可以反復(fù)聲明:
const num = 5; const num = 7; // SyntaxError: identifier 'num' has already been declaredvar x = 2; // x = 2 var x = 4; // x = 4?
??const 用于不會(huì)改變的值。
??const x = {} , 可以改變其內(nèi)的屬性值,或增加新的key/value對(duì)兒。
這是因?yàn)?#xff0c;const variables當(dāng)處理arrays 或objects時(shí)會(huì)改變,
技術(shù)上講,不是re-assign分配一個(gè)新的值給它,而是僅僅改變內(nèi)部的元素。
const farm = []; farm = ['rice', 'beans', 'maize'] // TypeError: Assignment to constant variable//但可以 farm.push('rice')?
Hoisting
Declarations will be brought to the top of the execution of the scope!
?? var x = "hello" 這種聲明加分配assign的寫法無法Hoisting!!
?? 函數(shù)聲明也可以Hoisting.
?
Closures
lexical or function closures.
用于把函數(shù)和周圍的state(var, const, let聲明的變量,函數(shù)。)綁定一起使用。
換句話說,closure給你入口進(jìn)入到函數(shù)作用域外面的區(qū)域,并使用這個(gè)區(qū)域的變量,函數(shù)。
function jump() {var height = 10;function scream() {console.log(height);}return scream; }var newJump = jump() //function runs but doesnot log anything newJump(); //logs 10在函數(shù)jump中聲明了height, 它只存在于函數(shù)作用域內(nèi)。
通過Closure, 函數(shù)scream得到了height。
執(zhí)行函數(shù)jump, 并把函數(shù)scream存入一個(gè)新的變量newJump, 這個(gè)newJump就是一個(gè)函數(shù)
執(zhí)行newJump(), 就是執(zhí)行scream。 而scream可以引用jump內(nèi)的height。
JavaScript所做的是保持一個(gè)對(duì)原始作用域的引用,我們可以使用它和height變量。
這個(gè)引用就叫做closure。
?
另一個(gè)例子:
function add (a) {return function (b) {return a + b}; }// use var addUp7 = add(7) var addUp14 = add(14)console.log (addUp7(8)); // 15 console.log (addUp14(12)); // 26addUp7和addUp14都是closures。
例如:
addup7創(chuàng)造了一個(gè)函數(shù)和一個(gè)變量a。a的值是7。
執(zhí)行addUp7(8), 會(huì)返回a + 8的結(jié)果15。
?
為什么要使用閉包c(diǎn)losures?
開發(fā)者總是尋找更簡潔和高效的編碼方式,來簡化日常工作和讓自己更多產(chǎn)。
理解和使用closures就是其中的一個(gè)技巧。使用closures有以下好處:
1. Data Encapsulation?
closures可以把數(shù)據(jù)儲(chǔ)存在獨(dú)立的scope內(nèi)。
例子:
在一個(gè)函數(shù)內(nèi)定義一個(gè)class
//使用(function(){}())在函數(shù)聲明后馬上執(zhí)行,需要用()括起來。 (function () {var foo = 0function MyClass() {foo += 1;};MyClass.prototype = {howMany: function() {return foo;}};window.MyClass = MyClass; }());foo可以通過MyClass constructor存入和howMany方法取出。
即使IIFE方法被執(zhí)行后退出, 變量foo仍然存在。MyClass通過closure功能存取它的值。
?
2.Higher Order Functions
簡化多層嵌套的函數(shù)的代碼。
//x從它被定義的位置被一步步傳遞到它被使用的位置。function bestSellingAlbum(x) { return albumList.filter(function (album) { return album.sales >= x; });}filter自動(dòng)獲取了x,這就是閉包的作用。
如果沒有closures, 需要寫代碼把x的值傳遞給filte方法。
?
現(xiàn)在使用ES6, 代碼就更簡單了。
const bestSellingAlbums = (x) => albumList.filter(album => album.sales >= x);?
?
Closures的實(shí)踐
1.和對(duì)象化編程一起使用
//聲明一個(gè)函數(shù)對(duì)象 function count() {var x = 0;return {increment: function() { ++x; },decrement: function() { --x; },get: function() { return x; },reset: function() { x = 0; }} }?
執(zhí)行這個(gè)函數(shù)
var x = count(); x.increment() //返回1 x.increment() //返回2 x.get() //返回2 x.reset() //重置內(nèi)部變量x為0??
2.傳遞值和參數(shù)進(jìn)入一個(gè)算法。
function proximity_sort(arr, midpoint) {return arr.sort(function(x, y) { x -= midpoint; y -= midpoint; return x*x - y*y; }); }?
3. 類似namspace的作用。
var houseRent = (function() {var rent = 100000;function changeBy(amount) {rent += amount;}return {raise: function() {changeBy(10000);},lower: function() {changeBy(-10000);},currentAmount: function() {return rent;}};})();houseRent可以執(zhí)行raise, lower, currentAmount函數(shù)。但不能讀取rent,changeBy函數(shù)。
?
Closures在函數(shù)編程中的2個(gè)重要concepts(不理解?)
- partial application 局部應(yīng)用
- currying 梳理(?)
Currying是一種簡單的創(chuàng)建函數(shù)的方法,這種方法會(huì)考慮一個(gè)函數(shù)的參數(shù)的局部使用。
簡單來說,一個(gè)函數(shù)接受另一個(gè)函數(shù)和多個(gè)參數(shù),并返回一個(gè)函數(shù)及較少的參數(shù)。
Partial application搞定了在返回函數(shù)中的一個(gè)或多個(gè)參數(shù)。
返回的函數(shù)接受了剩下的parameters作為arguments來完成這個(gè)函數(shù)應(yīng)用。
partialApplication(targetFunction: Function, ...fixedArgs: Any[]) =>functionWithFewerParams(...remainingArgs: Any[])?
使用array的普通方法的內(nèi)部結(jié)構(gòu)來理解這2個(gè)概念:
Array.prototype.map()方法
map用來創(chuàng)建一個(gè)新的array。 調(diào)用一個(gè)函數(shù)作為參數(shù),這個(gè)函數(shù)應(yīng)用到每個(gè)array元素上,并返回結(jié)果。
var new_array = arr.map(function callback(currentValue[, index[, array]]) {// Return element for new_array }[, thisArg])?
參數(shù)Parameters:
- callback:函數(shù),用于創(chuàng)建新array的元素,它接受3個(gè)參數(shù),第一是必須的:
- currentValue: 在array中,正在被執(zhí)行的元素。
- index:? current element在array 中的索引。
- array: 調(diào)用map方法的數(shù)組本身。
- thisArg: 當(dāng)執(zhí)行callback時(shí),作為this本身。
Return value:
一個(gè)新的array,每個(gè)元素是被callback函數(shù)處理過的。
內(nèi)部結(jié)構(gòu):
Array.prototype.map = function(callback) { arr = [];for (var i = 0; i < this.length; i++)arr.push(callback(this[i],i,this));return arr;};?
Array.prototype.filter()方法
和map結(jié)構(gòu)類似,但是,callback函數(shù)用來測(cè)試每個(gè)數(shù)組中的元素。如果返回ture則保留這個(gè)元素。
?
?
?
Data Structures: Objects and Arrays
相比String, Number, Boolean, Null, Undefined更復(fù)雜的數(shù)據(jù)結(jié)構(gòu)。可以看作是其他數(shù)據(jù)結(jié)構(gòu)的容器。
一般來說,幾乎everything in JS is an Object. 因此, JS可以看成是對(duì)象化編程語言。
在瀏覽器中,一個(gè)window加載后,Document對(duì)象的一個(gè)實(shí)例就被創(chuàng)建了。
在這個(gè)頁面上的所有things都是作為document object的child。
Document methods是用來對(duì)父對(duì)象進(jìn)行相關(guān)的操作。
const myObject = {myKey1: 'ObjectValue1',myKey2: 'ObjectValue2',mykeyN: 'ObjectValueN',objectMethod: function() {// Do something on this object } };?
?
為什么說everything is an Object?
const myMessage = "look at me!"這個(gè)數(shù)據(jù)類型是字符串。
但其實(shí)它是由String對(duì)象生成的實(shí)例instance,通過_proto_屬性,可以調(diào)用String中的methods.
如
String.prototype.toUpperCase.
myMessage.toUpperCase()??
??:
myMessage是String的一個(gè)實(shí)例,myMessage的_proto_屬性,就是String.prototype。
實(shí)例myMessage通過_proto_屬性,調(diào)用String中儲(chǔ)存在prototype上的方法。
// simple way to create a string const myMessage = 'look at me go!';// what javascript sees const myOtherMessage = String('look at me go!');myMessage == myOtherMessage; // true擴(kuò)展知識(shí)點(diǎn):見博客:原型對(duì)象和prototype(https://www.cnblogs.com/chentianwei/p/9675630.html)
?
constructor屬性
還是說上面的例子,String實(shí)例myMessage的數(shù)據(jù)類型是什么:
typeof myOtherMessage //返回 "string"?
這是如何構(gòu)建的?使用實(shí)例的constructor屬性:
myOtherMessage.constructor //得到,? String() { [native code] }?
?
由此可知myOtherMessage變量用于存儲(chǔ)一個(gè)字符串。它本身是由String構(gòu)造的實(shí)例對(duì)象。
everything is object,理解了把!
?
"this" Keyword
詳細(xì)看(博客)(或者YDJS對(duì)應(yīng)的章節(jié))
4條rule:
使用方法:
先找到call-site,然后檢查符合哪條rule。
call-site,即一個(gè)函數(shù)被調(diào)用的地點(diǎn),也可以說一個(gè)函數(shù)所處的execution context。
?
優(yōu)先級(jí):
new > explicit > implicit > default
?
Rule 1: Default (Global) Binding
?
Rule 2: Implicit Binding
根據(jù)call-site。根據(jù)對(duì)象。
例子:
var company = {name: 'Baidu',printName() {console.log(this.name)} }var name = 'google'company.printName() // Baidu, 因?yàn)閜rintName()函數(shù)被company對(duì)象調(diào)用。var printNameAgain = company.printNameprintNameAgain(); // google, 因?yàn)檫@個(gè)函數(shù)被全局對(duì)象調(diào)用。?
?
Rule 3: Explicit Binding
可以明確指定調(diào)用點(diǎn)。
使用call, apply ,bind方法。傳遞對(duì)象作為參數(shù)。第一個(gè)參數(shù)是一個(gè)對(duì)象,它被傳遞給this關(guān)鍵字。
因此this指向就明確了。
//根據(jù)上例子 printNameAgain.call(company) // Baidu.?
call(), 可以傳遞string, 數(shù)字等作為其他參數(shù)。
apply(), 只能接受一個(gè)數(shù)組作為第2個(gè)參數(shù).
?
bind()最為特殊,它會(huì)綁定一個(gè)context。然后返回這個(gè)函數(shù)和調(diào)整后的context。
var printFunc = printNameAgain.bind(company) //printFunc是printNameAgain函數(shù),并綁定company對(duì)象, this永遠(yuǎn)指向company。 printFunc() // Baidu?
?
Rule 4: Constructor Calls with new
使用函數(shù)構(gòu)造調(diào)用。如new Number()
注意:
constructor就是一個(gè)函數(shù),和new操作符一起在被調(diào)用時(shí)運(yùn)行。和類無關(guān)也不實(shí)例化類!就是一個(gè)標(biāo)準(zhǔn)的函數(shù)。
當(dāng)一個(gè)函數(shù)前面有一個(gè)new, 會(huì)自動(dòng)做以下事情:
第3句:新構(gòu)建的對(duì)象被設(shè)置為this, 這個(gè)對(duì)象和new-invoked函數(shù)調(diào)用綁定在一起。
function Company() {this.name = 'baidu' }var b = new Company()//當(dāng)執(zhí)行代碼時(shí),會(huì)發(fā)生: function Company() {// var this = {};this.name = 'Scotch'// return this; 給變量b。 }?
由此可知:
第4句:默認(rèn)情況下,使用new關(guān)鍵字的函數(shù),會(huì)自動(dòng)地返回新構(gòu)建的對(duì)象。除非明確指定返回對(duì)象。
?
Async Handling
在異步邏輯時(shí),函數(shù)回調(diào)可能存在this binding的陷阱。
因?yàn)檫@些handers往往綁定一個(gè)不同的context,讓this的行為產(chǎn)生非期待的結(jié)果。
?
Event handing就是一個(gè)例子。事件處理器是回調(diào)函數(shù)。在運(yùn)行時(shí),當(dāng)事件被激活,回調(diào)函數(shù)被執(zhí)行。
瀏覽器需要提供和這個(gè)event相關(guān)的contextual information。它會(huì)綁定到回調(diào)函數(shù)中的this關(guān)鍵字。
?
以下代碼,在執(zhí)行后可以看到this的綁定對(duì)象:
button.addEventListener('click', function() {console.log(this) });?
?
假如你希望產(chǎn)生某個(gè)行為:
var company = {name: 'Scotch',getName: function() {console.log(this.name)} }// This event's handler will throw an error button.addEventListener('click', company.getName)?
因?yàn)闉g覽器提供的contextual info內(nèi),不一定有name這個(gè)屬性。所以可能會(huì)報(bào)告?。
告訴你name property is not existed。
或者有這個(gè)name屬性,但返回的值肯定不是你想要的結(jié)果。
所以需要使用bind()方法,明確指定this的綁定:
button.addEventListener('click', company.getName.bind(company))?
?
?
Basic Deisgn Patterns?
軟件工程設(shè)計(jì),存在大量不同的設(shè)計(jì)模式。
JS是一種非傳統(tǒng)的面向?qū)ο蟮木幊陶Z言。
?
設(shè)計(jì)模式(全免介紹不同的JS設(shè)計(jì)模式)
(https://www.dofactory.com/javascript/design-patterns)
?
3種設(shè)計(jì)模式分類:?
Creational patterns:
這種模式集中在創(chuàng)建對(duì)象。當(dāng)在一個(gè)大型程序種創(chuàng)建對(duì)象時(shí),有讓對(duì)象變復(fù)雜的趨向。通過控制對(duì)象的創(chuàng)建,Creational design patterns創(chuàng)造式設(shè)計(jì)模式可以解決這個(gè)問題。
?
Structural patterns:
這種模式提供了方法,用于管理對(duì)象和對(duì)象的關(guān)系,以及創(chuàng)建class structure。
其中一種方法是通過使用inheritance繼承, 和composition,從多個(gè)小的對(duì)象,到創(chuàng)建一個(gè)大的對(duì)象。
?
Behavioral patterns
這種模式集中在對(duì)象之間的交互上。
?
區(qū)別:
- Creational patterns描述了一段時(shí)間。
- Structural patterns描述了一個(gè)或多或少的static structure。
- 而Behavioral patterns描述了一個(gè)process, a flow。
?
?
Creational Patterns
Module模塊
這種模式常用于軟件開發(fā),這個(gè)module pattern可以被看作?Immediately-Invoked-Function-Expression?(IIFE).
(function() {// code goes here! })();?
所有module代碼在一個(gè)closure內(nèi)存在。
Variables通過執(zhí)行函數(shù)傳入value來進(jìn)口imported, 并返回一個(gè)對(duì)象來出口exported。
?
這種Modules比單獨(dú)的函數(shù)使用的方法有優(yōu)勢(shì):
它能夠讓你的global namespace 更干凈,更可讀性,也讓你的函數(shù)可以importable and exportable.
一個(gè)例子:
const options = {username: 'abcd',server: '127.0.0.1' };const ConfigObject = (function(params) {// return the publicly available things// able to use login function at the top of this module since it is hoistedreturn {login: login};const username = params.username || '',server = params.server || '',password = params.password || '';function checkPassword() {if (this.password === '') {console.log('no password!');return false;}return true;}function checkUsername() {if (this.username === '') {console.log('no username!');return false;}return true;}function login() {if (checkPassword() && checkUsername()) {// perform login }}})(options);?
?
Builder
這種模式的典型就是jQuery,雖然現(xiàn)在不再使用它了。
const myDiv = $('<div id="myDiv">This is a div.</div>'); // myDiv now represents a jQuery object referencing a DOM node. const myText = $('<p/>'); // myText now represents a jQuery object referencing an HTMLParagraphElement. const myInput = $('<input />'); // myInput now represents a jQuery object referencing a HTMLInputElement?
這種模式,讓我們構(gòu)建對(duì)象而無需創(chuàng)建這個(gè)對(duì)象,我們需要做的是指定數(shù)據(jù)type和對(duì)象的content。
這種模式的關(guān)鍵:
It aims at separating an object’s construction from its representation
我們無需再設(shè)計(jì)construction了。只提供內(nèi)容和數(shù)據(jù)類型即可。
?
?$?variable adopts the Builder Pattern in jQuery.
因此,無需再使用如document.createElement('div')等傳統(tǒng)的創(chuàng)建node的method。
?
除了Module和Builder,Creational Patterns還有Factory Method, Prototype, Singleton
Abstract Factory Creates an instance of several families of classes Builder Separates object construction from its representation Factory Method Creates an instance of several derived classes Prototype A fully initialized instance to be copied or cloned Singleton A class of which only a single instance can exist
?
?
Structural Patterns
Facade
A single class that represents an entire subsystem
這種模式:簡單地把一大片邏輯隱藏在一個(gè)簡單的函數(shù)調(diào)用中function call。
內(nèi)部的子程序和layers也被隱藏,并通過a facade來使用。
這種模式讓開發(fā)者看不到它的內(nèi)部結(jié)構(gòu)。開發(fā)者也無需關(guān)心它。
例子:
$(document).ready(function() {// all your code goes here... });?
Composites
Composites are objects composed of multiple parts that create a single entity.?
A tree structure of simple and composite objects
例子:?
$('.myList').addClass('selected'); $('#myItem').addClass('selected');// dont do this on large tables, it's just an example. $('#dataTable tbody tr').on('click', function(event) {alert($(this).text()); });?
?
其他模式:
Adapter Match interfaces of different classesBridge Separates an object’s interface from its implementationComposite A tree structure of simple and composite objectsDecorator Add responsibilities to objects dynamicallyFacade A single class that represents an entire subsystemFlyweight A fine-grained instance used for efficient sharingProxy An object representing another object?
?
?
?
Behavioral patterns
Observer
The observer design pattern implements a single object which maintains a reference to a collection of objects and broadcasts notifications when a change of state occurs. When we don’t want to observe an object, we remove it from the collection of objects being observed.
?
Vue.js對(duì)Vue實(shí)例中 data屬性的追蹤,應(yīng)該是一個(gè)Observer pattern。
?
結(jié)論:
沒有完美的設(shè)計(jì)模式。各種模式都是為了更好的寫web app。
相關(guān)書籍:
"Learning JavaScript Design Patterns" by?Addy Osmani?
?
?
Callbacks, Promises, and Async
?
函數(shù)是First-Class Objects:
1.函數(shù)可以被當(dāng)作value,分配給變量
2.可以嵌套函數(shù)
3.可以返回其他函數(shù)。
?
Callback Functions?
當(dāng)一個(gè)函數(shù)簡單地接受另一個(gè)函數(shù)作為參數(shù)argument, 這個(gè)被當(dāng)作參數(shù)的函數(shù)就叫做回調(diào)函數(shù)。
使用回調(diào)函數(shù)是函數(shù)編程的核心概念。
例子:
setInterval(),每間隔一段time, 調(diào)用一次回調(diào)函數(shù)。
setInterval(function() {console.log('hello!'); }, 1000);var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);
?
例子:
Array.map(), 把數(shù)組中的每個(gè)元素,當(dāng)作回調(diào)函數(shù)的參數(shù),有多少元素,就執(zhí)行多少次回調(diào)。最后返回一個(gè)新的array.
?
Naming Callback functions
回調(diào)函數(shù)可以被命名,回調(diào)函數(shù)可以是異步的。setInterval()中的函數(shù)就是異步函數(shù)。
function greeting(name) {console.log(`Hello ${name}, welcome to here!`) }function introduction(firstName, lastName, callback) {const fullName = `${firstName} ${lastName}` callback(fullName) }introduction('chen', 'ming', greeting) // Hello chen ming, welcome to here!
?
當(dāng)執(zhí)行introduction()時(shí),greeting函數(shù)被當(dāng)作參數(shù)傳入,并在introduction內(nèi)部執(zhí)行。
?
回調(diào)地獄Callback hell
function setInfo(name) {address(myAddress) {officeAddress(myOfficeAddress) {telephoneNumber(myTelephoneNumber) {nextOfKin(myNextOfKin) {console.log('done'); //let's begin to close each function! };};};}; }?
除了不好看外,當(dāng)變復(fù)雜后,傳統(tǒng)的回調(diào)函數(shù)調(diào)用還會(huì)出現(xiàn)回調(diào)函數(shù)調(diào)用過早,或者過晚,等等問題
具體看這篇博客https://www.cnblogs.com/chentianwei/p/9774098.html
?
Promises
因?yàn)镻romises封裝了時(shí)間依賴狀態(tài)the time-dependent state?---等待滿足或拒絕這個(gè)潛在的value--從外部,因此Promises可以被composed(combined, 比如x和y做加法運(yùn)算)
一旦一個(gè)Promise被解決,它就是一個(gè)不變的值,如果需要可以多次被observed。
?
Promises是一個(gè)方便的可重復(fù)的機(jī)制用于封裝和組織furture value。
?
Promise有3個(gè)狀態(tài):
- Pending: 初始狀態(tài),在一個(gè)操作開始前的狀態(tài).
- Fulfilled: 當(dāng)指定的操作被完成后的狀態(tài)。
- Rejected: 操作未完成,或者拋出一個(gè)?值
?
?
var weather = true const date = new Promise(function(resolve, reject) {if (weather) {const dateDetails = {name: 'Cubana Restaurant',location: '55th Street',table: 5};resolve(dateDetails)} else {reject(new Error('Bad weather, so no Date'))} });?
date的值是一個(gè)Promise對(duì)象,其中:
屬性[[PromiseStatus]]的值是"resolved",
(如果weather = false, 最后date中的屬性[[PromiseStatus]]的值是"rejected")
屬性[[PromiseValue]]的值是一個(gè)對(duì)象.
?
使用Promise對(duì)象
當(dāng)?shù)玫絧romise對(duì)象后,可以使用then(), catch(),調(diào)用回調(diào)函數(shù),
對(duì)promise對(duì)象進(jìn)行進(jìn)一步操作,并返回一個(gè)新的promise對(duì)象。
當(dāng)Promise對(duì)象中的屬性[[PromiseStatus]]的值:
- resolve,會(huì)調(diào)用then()
- rejecte,? ?會(huì)調(diào)用catch().
例子:
const weather = false const date = new Promise(function(resolve, reject) {if (weather) {const dateDetails = {name: 'Cubana Restaurant',location: '55th Street',table: 5};resolve(dateDetails)} else {reject('Bad weather, so no Date')} });date
.then(function(done) {
//
})
.catch(function(err){console.log(err)})
//最后輸出'Bad weather, so no Date'
?
我們使用?創(chuàng)建的promise對(duì)象date(weather變量的值是true, 返回resolve(dateDetails)。)
const myDate = function() {date.then(function(done) {console.log("We are going on a date!")console.log(done)}).catch(function(err) {console.log(err)}) }myDate()
?
得到結(jié)果:
We are going on a date! // console.log(done) 在控制臺(tái)界面顯示done參數(shù)。 {name: "Cubana Restaurant", location: "55th Street", table: 5}location: "55th Street"name: "Cubana Restaurant"table: 5__proto__: Object?
由此可見,.then()中,給回調(diào)函數(shù)的參數(shù)done,其實(shí)就是promise對(duì)象date中的[[PromiseValue]]。
而date是執(zhí)行resolve(dateDetails)函數(shù)后返回的結(jié)果。
因此,.then()接收的參數(shù)就是promise對(duì)象date的resolve()的值。
而,? .catch()接收的參數(shù)是promise對(duì)象date的reject()的值。
?
??Promises是異步的。Promises在函數(shù)中被放置在一個(gè)小的工作棧內(nèi),并在其他同步操作完成后運(yùn)行run。
?
Chaining Promises
如果基于the result of preceding promises來執(zhí)行2個(gè)以上的異步操作時(shí),需要chain promises。
還是使用上面的代碼:
//創(chuàng)建一個(gè)新的promise const order = function(dateDetails) {return new Promise(function(resolve, reject) {const message = `Get me an ASAP to ${dateDetails.location}, We are going on a date!`resolve(message)}) }?
簡化寫法:
const order = function(dateDetails) {const message = `Get me an Asap to ${dateDetails.location}, We are going on a date`return Promise.resolve(message) }然后,我們就可以chain連接之前寫的Promise對(duì)象date了,
這是因?yàn)閳?zhí)行order函數(shù)會(huì)返回一個(gè)新的promise對(duì)象。
const myDate = function() {date.then(order) //傳入回調(diào)函數(shù)order.then(function(done) { //...}).catch(function(err) { console.log(err.message)}) }myDate()
?
?
?
Async and Await?(點(diǎn)擊查看文檔說明)
EMS2017中的新語法糖。僅僅讓寫promise更容易。但老的瀏覽器不支持。
在一個(gè)函數(shù)前加上async關(guān)鍵字,這個(gè)函數(shù)會(huì)返回一個(gè)promise對(duì)象。
如果函數(shù)返回的值是true, promise中的[[PromiseState]]的值將是'resolved'。
但是函數(shù)返回的值是false, async function會(huì)拋出?,promise中的[[PromiseState]]的值將是'rejected'
async function myRide() {return '2017' }?等同于
function yourRide() {return Promise.resolve('2017') }如果函數(shù)返回false:
function foo() {return Promise.reject(25) } // is equal to async function() {throw 25 }?
Await
和async function配套使用的關(guān)鍵字(語法糖)
用于保證所有在async function中返回的promises是同步的。
await等待其他promise執(zhí)行完成,然后在執(zhí)行后續(xù)代碼。
?
async在返回一個(gè)promise前是等待狀態(tài)。
await在調(diào)用一個(gè)promise前是等待狀態(tài)。
?
async function myDate() {try {let dateDetails = await date;let message = await order(dateDetails)console.log(message)} catch(err) { console.log(err.message)} }(async () => {
? await myDate();
})()
?
?
?
回顧
Es6是Js的核心版本,每個(gè)js developer必須掌握的。
?
?
Promises in ES6
在promise出現(xiàn)之前,開發(fā)者不得不大量使用callbacks。
setTimeout, XMLHttpRequest是基本的基于瀏覽器的異步函數(shù)的回調(diào)。
setTimeout(function() {console.log('Cool!') }, 1000);?
使用Promise:
let lunchTime = new Promise(function(eat, skip) {setTimeout(eat, 1000) }).then(function() {console.log('lunch time!') })?
使用ES6箭頭函數(shù)更方便:
let lunchTime = new Promise((eat, skip) => setTimeout(eat, 1000)).then(() => console.log('Lunch Time!'))?
隨著應(yīng)用開發(fā),代碼的邏輯會(huì)更加的復(fù)雜,promise可以更好的處理這些邏輯:
//聲明的變量儲(chǔ)存一個(gè)函數(shù) var lunchTimeDelay1000 = () => new Promise((eat, skip) => { setTimeout(eat, 1000) })//使用2次.then()執(zhí)行不同的邏輯: //第一個(gè)then()內(nèi),返回lunchTimeDelay1000的執(zhí)行,即返回原promise對(duì)象,以便執(zhí)行下一個(gè)邏輯 lunchTimeDelay1000().then(function() {console.log('Lunch Time!');return lunchTimeDelay1000();}).then(function() {console.log('Good Food!');});如此,代碼非常容易理解,運(yùn)行代碼,等待1秒,然后繼續(xù)運(yùn)行代碼,再等待,并可以再運(yùn)行更多代碼。
?
Variable Declaration in ES6
新版使用let, const, var的使用范圍被減少。
?
Multi Line Strings in ES6
傳統(tǒng)字符串,換行用\n, 叫做backslash
ES6,可以使用backticks,反引號(hào) ``, 然后直接回車換行。
const drSeuss = `My name is Sam I AmI do not like green eggs and hamLunchtime is here. Come and eat `;等同于:
const drSeuss = 'My name is Sam I Am,\n' + 'I do not like green eggs and ham,\n' + 'Lunchtime is here. Come and eat'?
稱為:ES6 template strings,模版字符串。
template strings的另一個(gè)功能,可以插入變量, 使用${}
?
Destructuring Assignment in ES6? 拆解賦值
見對(duì)象x:
var x = {fish: 1, meat: 2} fish = x.fish //1 meat = x.meat // 2//使用ES6 var {fish, meat} = x?
?注意??,變量fish, meat,這2個(gè)identifier,在x中有對(duì)應(yīng)的屬性fish和meat。如果沒有,則無法賦值。
?
array也可以拆分分配
具體見之前的博客:https://www.cnblogs.com/chentianwei/p/10153866.html
例子:
for..of顯示一個(gè)array的內(nèi)容
var arr = [["a", 1],["b", 2],["c", 3] ]for (let [key, value] of arr) {console.log(`${key}: ${value}`) }//輸出 a: 1 b: 2 c: 3?
?
Object Literals in ES6
object Literals的一些簡化和改進(jìn):
- 在object construction上建立prototype (未理解用途)
- 簡化方法聲明
- Make super calls? (未理解用途)
- Computed property names
例子:典型的ES5對(duì)象字面量,內(nèi)有一些方法和屬性。這里使用了ES6的模版string功能:
var objectManager = {port: 3000,url: 'manage.com' };const getAccounts = function() {return [1, 2, 3]; }var manageObjectES5 = {port: objectManager.port,url: objectManager.url,getAccounts: getAccounts,toString: function() {return JSON.stringify(this.valueOf());},getUrl: function() {return `http://${this.url}:${this.port}`; },valueOf_1_2_3: getAccounts(); };?
使用ES6的功能:
const manageObject = {proto: objectManager,getAccounts,// Also, we can invoke super and have dynamic keys (valueOf_1_2_3): toString() {return JSON.stringify((super.valueOf()))},getUrl() {return "http://" + this.proto.url + ':' + this.proto.port},['valueOf_' + getAccounts().join('_')]: getAccounts() };getAccounts, 引用一個(gè)函數(shù),只要名字相同就可以簡化方法聲明。
super關(guān)鍵字:
用于存取和調(diào)用對(duì)象的父對(duì)象上的函數(shù)。
super.prop, super[expr]表達(dá)式可以通過任何在classes和object literals中的方法定義的驗(yàn)證。
super([arguments]); // calls the parent constructor. super.functionOnParent([arguments]);['valueOf_' + getAccounts().join('_')]: 可以使用通過計(jì)算得到的屬性名字。
?
Arrow Functions in ES6
箭頭函數(shù)中的this.指向調(diào)用函數(shù)的對(duì)象。
const stringLowerCase = function() {this.string = this.string.toLowerCase();return () => console.log(this.string); }stringLowerCase.call({string: 'JAVASCRIPT' })()?
注意,只有一行的代碼的時(shí)候,使用箭頭函數(shù),可以省略return
let sayHello = () => 'hello'?
?
Default Parameters in ES6
小的功能的改進(jìn)
var garage = function(model, color, car) {var model = model || "Mustang"var color = color || 'blue'var car = car || 'Ford' }//ES6 var garage = function(model = 'Mustang', color = 'blue', car = 'Ford') {// ... }?
?
Template Literals in ES6
var x =10 var y = 20 console.log(`Thirty is ${x + y}`) `\`` === '`' // --> true?
在backticks反引號(hào)內(nèi)使用dollar sign and curly braces: ${ //... }
?
Nesting templates
可以在一個(gè)template內(nèi)使用``, 即嵌套模版。
var classes = 'header' classes += (isLargeScreen() ?'' : item.isCollapsed ?' icon-expander' : ' icon-collapser');//使用ES6的template,但不嵌套 const classes = `header ${ isLargeScreen() ? '' :(item.isCollapsed? 'icon-expander : 'icon-collapser'') }`//使用嵌套模版,這里的作用是把'icon'字符串提煉出來。(這里只是演示,用途不大) const classes = `header ${ isLargeScreen() ? '' :`icon-${item.isCollapsed ? 'expander' : 'collapser'}` }`;?
?
?
Classes in ES6
在Js的存在的prototype-based 繼承上的語法糖。
簡化了傳統(tǒng)的寫法。可以像傳統(tǒng)的對(duì)象類一樣,使用class句法。但核心未變(prototype-based inheritance)。
?
定義classes
classes只不過是特殊的函數(shù)。
就像可以定義函數(shù)表達(dá)式和函數(shù)聲明。class句法也有2個(gè)組件:
- ?class expressions:是在ES6中定義一個(gè)類的一個(gè)方法,還可以類聲明。
- ?class declarations:? 用一個(gè)名字來創(chuàng)建一個(gè)新的class。用到prototype-based inheritance.?
?
?
class expressions
和class statement(declaration)有類似的句法結(jié)構(gòu)。但是,
如果一個(gè)類表達(dá)式使用一個(gè)name,這個(gè)name會(huì)存在類表達(dá)式的body內(nèi)。
class declarations
只能定義一次,之后不能再修改。
注意,類聲明不能被hoisting。所以必須先聲明,再使用。否則會(huì)報(bào)錯(cuò)?。
?
Class body and method definitions
所有的類成員都寫在body內(nèi),即{ }內(nèi)。如methods or constructor。
Constructor
這是一個(gè)特殊的方法,用于創(chuàng)建和初始化initializing一個(gè)對(duì)象。
一個(gè)類內(nèi)只能有一個(gè)constructor方法。否則拋出?。
Prototype methods
從ES6開始,關(guān)于對(duì)象初始化的方法定義的簡單句法被引進(jìn)。
var obj = {property(params...) {},*generator(params...) {},async property(params...) {},async *generator(params...) {},//使用計(jì)算的keys [property](params...) {}, *generator(params...) {},async property(params...) {},//使用比較句法 getter/setter, 定義一個(gè)非函數(shù)屬性。 get property() {}set property() {} }?
The shorthand syntax is similar to the?getter?and?setter?syntax introduced in ECMAScript 2015.
例子:
var bar = {foo0() { return 0 },foo1() { return 1 },['foo' + 2]() { return 2} }?
?
Instance properties
實(shí)例屬性必須定義在class methods內(nèi)。
class Rectangle {constructor(height, width) { this.height = height;this.width = width;} }?
Static methods
static關(guān)鍵字定義了靜態(tài)方法。調(diào)用靜態(tài)方法無需實(shí)例化類,也不能被類實(shí)例調(diào)用(就是類方法)
class Point {constructor(x, y) {this.x = x;this.y = y;}static distance(a, b) {const dx = a.x - b.x;const dy = a.y - b.y;return Math.hypot(dx, dy);} }const p1 = new Point(5, 5); const p2 = new Point(10, 10);console.log(Point.distance(p1, p2));??
類的繼承: extends關(guān)鍵字
ES6增加了extends關(guān)鍵字來創(chuàng)建一個(gè)類的子類。
例子:
本例子,在子類的constructor內(nèi)使用了super關(guān)鍵字。
//使用了ES6的句法:class Animal { constructor(name) {this.name = name;}speak() {console.log(this.name + ' makes a noise.');} } //如果一個(gè)constructor在子類中存在,它需要調(diào)用super()后,才能使用this. class Dog extends Animal {constructor(name) { super(name); // call the super class constructor and pass in the name parameter }speak() {console.log(this.name + ' barks.');} }let d = new Dog('Mitzie'); d.speak(); // Mitzie barks.
// 如果Dog不使用constructor函數(shù),也可以。但使用的化,必須配合super()。
?
另外,可以使用傳統(tǒng)的function-based "classes"
function Animal (name) {this.name = name; }Animal.prototype.speak = function () {console.log(this.name + ' makes a noise.'); }class Dog extends Animal {speak() {console.log(this.name + ' barks.');} }let d = new Dog('Mitzie'); d.speak(); // Mitzie barks.?
再次強(qiáng)調(diào),JavaScript的類是prototype-based的
Dog.prototype//Animal {constructor: ?, speak: ?}
?
?
類classes 不能extend標(biāo)準(zhǔn)對(duì)象(non-constructible)。
因此,如果你想要繼承自一個(gè)regular object。你需要使用方法Object.setPrototypeof()方法
const Animal = {speak() {console.log(this.name + 'makes a noise')} }class Dog {constructor(name) { this.name = name} }Object.setPrototypeOf(Dog.prototype, Animal)let d = new Dog('wang') d.speak()?
?
使用super關(guān)鍵字可以調(diào)用父類的方法
除了上文提到的在子類的constructor中使用super(params...),
還可以在子類中的方法中使用super.
例子:
class Lion extends Cat {speak() {super.speak();console.log(`${this.name} roars.`);} }?
Modules in ES6
在ES6之前,JS不支持modules。現(xiàn)在有了import和export操作符。
在ES5, 常見使用<script>標(biāo)簽和IIFE(即使用()();),或者AMD之類的庫。實(shí)現(xiàn)類似功能。
?
流行的寫法:
//module.js export var port = 3000 export function getCar(model) {...}//main.js import {port, getCar} from 'module';可選的,使用as關(guān)鍵字把引進(jìn)的存入一個(gè)變量:
import * as service from 'module' console.log(service.port) //3000語法:
//輸出變量name1, name2 export { name1, nam2, } //使用別名 export { var1 as name1 } //聲明+賦值,然后輸出。(如果不賦值,則值默認(rèn)為undefined) export let name1 = 100 //輸出函數(shù), class都可以。 export function Name() {...}//輸出默認(rèn)的表達(dá)式, 函數(shù),class export default expression export { name1 as default, ...}export * from ...; export { name1, ...} from...; export { import as name1, ...} from ...; export { default} from ...;?
?
和ES5的寫法比較:
var s = "hello"export { s } //等同于,使用babel在線編輯器,可以看轉(zhuǎn)化格式。 exports.s = s//或者
module.exports = s
?
?
CommonJS規(guī)范
這種模塊加載機(jī)制被稱為CommonJS規(guī)范。在這個(gè)規(guī)范下,每個(gè).js文件都是一個(gè)模塊,它們內(nèi)部各自使用的變量名和函數(shù)名都互不沖突,例如,hello.js和main.js都申明了全局變量var s = 'xxx',但互不影響。
一個(gè)模塊想要對(duì)外暴露變量(函數(shù)也是變量),可以用
module.exports = variable;,
一個(gè)模塊要引用其他模塊暴露的變量,用
var ref = require('module_name');
?
深入了解模塊原理
JS語言本書并沒有一種機(jī)制保證不同的模塊可以使用相同的變量名。相同的變量名就會(huì)沖突!
但,實(shí)現(xiàn)模塊的奧妙在于: Closures!
把一段js代碼用一個(gè)函數(shù)包裹起來,這段代碼的"全局"變量,就成了函數(shù)內(nèi)的局部變量了!
?
首先了解一下, node.js的模塊加載原理:如何讓變量名不沖突。
//hello.js var s = 'Hello'; var name = 'world';console.log(s + ' ' + name + '!');//Node.js加載hello.js, 會(huì)使用IIFE (function () {// 讀取的hello.js代碼:var s = 'Hello';var name = 'world';console.log(s + ' ' + name + '!');// hello.js代碼結(jié)束 })();?
這樣,Node.js加載其他模塊時(shí),變量s都是局部的了。
?
再了解module.exports的實(shí)現(xiàn):
Node先準(zhǔn)備一個(gè)對(duì)象module,
// 準(zhǔn)備module對(duì)象: var module = {id: 'hello',exports: {} };?
然后:
module.exports = variables //這是我們要輸出的變量var load = function(module) {return module.exports; } var exported = load(module) //得到要輸出的內(nèi)容。//Node把module變量保存到某個(gè)地方 save(module, exported)
?
由于Node保存了所有導(dǎo)入的module,當(dāng)我們使用require()獲取module時(shí),Node找到對(duì)應(yīng)的module,把這個(gè)module的exports變量返回。 這樣另一個(gè)模塊就順利拿到了模塊的輸出:
var greet = require('./hello');?
?
ES6之后,直接使用關(guān)鍵字export和import即可!
?
getter?
get syntax綁定一個(gè)對(duì)象的屬性到一個(gè)函數(shù),當(dāng)屬性被調(diào)用(查詢)時(shí),執(zhí)行這個(gè)函數(shù)。
//Syntax {get prop() { ... } } {get [expression]() { ... } }?
介紹:
有時(shí)候,讓一個(gè)屬性能夠返回動(dòng)態(tài)的可計(jì)算的值,是非常方便的,
或者,你可能想要反應(yīng)這個(gè)內(nèi)部變量的status,卻無需使用明確的方法來調(diào)用。
在JavaScript,可以通過使用getter來完成。
??,一個(gè)屬性,不能同時(shí)既綁定一個(gè)函數(shù),又有一個(gè)明確的值。
//以下都是?的//屬性x,不能有多個(gè)函數(shù)綁定。
{ get x() { }, get x() { } }
//屬性x, 不能同時(shí)既有明確的值,又有函數(shù)生成的計(jì)算后返回的值。 { x: ..., get x() { } }
?
??,使用getter的屬性,只能有0個(gè)或1個(gè)參數(shù)。
??, delete 操作符,可以刪除一個(gè)getter。
例子:
在對(duì)象初始化時(shí),定義一個(gè)getter。
var obj = {log: [1, 2, 3],get latest() {if (this.log.length == 0) {return undefined;} return this.log[this.log.length - 1];} }console.log(obj.latest); // "3".?
// 使用delete操作符號(hào),刪除一個(gè)getterdelete obj.latest
obj.latest //undefined
?
getter也可以使用computed property name:
var expr = 'foo';var obj = {get ["You_" + expr]() {return 'hahaha!!!'} }obj.You_foo //"hahaha!!!"?
?
Smart/lazy/self-overwriting getters
默認(rèn)的getters,是懶惰的:
Getters可以讓你定義一個(gè)對(duì)象的屬性,但是如果你不存取(使用)它,這個(gè)屬性的值不會(huì)被計(jì)算。(類似函數(shù))
?
setter
set句法綁定一個(gè)對(duì)象的屬性到一個(gè)函數(shù),但想要用這個(gè)屬性改變什么,調(diào)用這個(gè)函數(shù)。
?
{set prop(val) {...}} {set [expression](val) {} }?
當(dāng)想要改變一個(gè)指定的屬性時(shí),調(diào)用這個(gè)函數(shù)。
setter和getter一起使用,創(chuàng)建一個(gè)偽屬性的類型。a type of pseudo-property。
??
必須有一個(gè)明確的參數(shù)。
禁止:(?{ set x(v) { }, set x(v) { } }?and?{ x: ..., set x(v) { } }
setter可以被delete方法刪除。
?
例子
在對(duì)象初始化時(shí)定義一個(gè)setter。
var language = {set current(name) {this.log.push(name)},log: [] }language.current = 'En' //"En" language.current = 'Fa' //"Fa" language.log //(2)?["En", "Fa"]?
??,因?yàn)闆]有使用getter,所以language.current會(huì)得到undefined。
?
如果要給已經(jīng)存在的對(duì)象,添加一個(gè)setter:使用
Object.defineProperty()
var o = {a: 0} Object.defineProperty(o, 'b', {set: function(x) { this.a = x/2}}) o.b = 10 o.a //5?
?
和getter一樣,setter也可以使用計(jì)算屬性名字。
?
結(jié)論
不是所有瀏覽器都支持ES6的所有功能。因此需要使用編譯器如Babel.?
Babel可以是Webpack的一個(gè)插件。也可以單獨(dú)作為tool使用。
關(guān)于為什么要使用編譯器:見這篇文章:
https://scotch.io/tutorials/javascript-transpilers-what-they-are-why-we-need-them
?
轉(zhuǎn)載于:https://www.cnblogs.com/chentianwei/p/10197813.html
總結(jié)
以上是生活随笔為你收集整理的JavaScript的几个概念简单理解(深入解释见You Don't know JavaScript这本书)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 简述模块-random
- 下一篇: MariaDB 视图与触发器(11)