日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

JavaScript的几个概念简单理解(深入解释见You Don't know JavaScript这本书)

發布時間:2025/7/14 javascript 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 JavaScript的几个概念简单理解(深入解释见You Don't know JavaScript这本书) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

ES201X是JavaScript的一個版本。

?

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個類型聲明用在Block Scope內。

?

聲明一次還是多次?

let, const只能聲明一次。但var聲明可以反復聲明:

const num = 5; const num = 7; // SyntaxError: identifier 'num' has already been declaredvar x = 2; // x = 2 var x = 4; // x = 4

?

??const 用于不會改變的值。

??const x = {} , 可以改變其內的屬性值,或增加新的key/value對兒。

這是因為,const variables當處理arrays 或objects時會改變,

技術上講,不是re-assign分配一個新的值給它,而是僅僅改變內部的元素。

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!!

?? 函數聲明也可以Hoisting.

?


Closures

lexical or function closures.

用于把函數和周圍的state(var, const, let聲明的變量,函數。)綁定一起使用。

換句話說,closure給你入口進入到函數作用域外面的區域,并使用這個區域的變量,函數。

function jump() {var height = 10;function scream() {console.log(height);}return scream; }var newJump = jump() //function runs but doesnot log anything newJump(); //logs 10

在函數jump中聲明了height, 它只存在于函數作用域內。

通過Closure, 函數scream得到了height。

執行函數jump, 并把函數scream存入一個新的變量newJump, 這個newJump就是一個函數

執行newJump(), 就是執行scream。 而scream可以引用jump內的height。

JavaScript所做的是保持一個對原始作用域的引用,我們可以使用它和height變量。

這個引用就叫做closure。

?

另一個例子:

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)); // 26

addUp7和addUp14都是closures。

例如:

addup7創造了一個函數和一個變量a。a的值是7。

執行addUp7(8), 會返回a + 8的結果15。

?

為什么要使用閉包closures?

開發者總是尋找更簡潔和高效的編碼方式,來簡化日常工作和讓自己更多產。

理解和使用closures就是其中的一個技巧。使用closures有以下好處:

1. Data Encapsulation?

closures可以把數據儲存在獨立的scope內。

例子:

在一個函數內定義一個class

//使用(function(){}())在函數聲明后馬上執行,需要用()括起來。 (function () {var foo = 0function MyClass() {foo += 1;};MyClass.prototype = {howMany: function() {return foo;}};window.MyClass = MyClass; }());

foo可以通過MyClass constructor存入和howMany方法取出。

即使IIFE方法被執行后退出, 變量foo仍然存在。MyClass通過closure功能存取它的值。

?

2.Higher Order Functions

簡化多層嵌套的函數的代碼。

//x從它被定義的位置被一步步傳遞到它被使用的位置。function bestSellingAlbum(x) { return albumList.filter(function (album) { return album.sales >= x; });}

filter自動獲取了x,這就是閉包的作用。

如果沒有closures, 需要寫代碼把x的值傳遞給filte方法。

?

現在使用ES6, 代碼就更簡單了。

const bestSellingAlbums = (x) => albumList.filter(album => album.sales >= x);

?

?

Closures的實踐

1.和對象化編程一起使用

//聲明一個函數對象 function count() {var x = 0;return {increment: function() { ++x; },decrement: function() { --x; },get: function() { return x; },reset: function() { x = 0; }} }

?

執行這個函數

var x = count(); x.increment() //返回1 x.increment() //返回2 x.get() //返回2 x.reset() //重置內部變量x為0

??

2.傳遞值和參數進入一個算法。

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可以執行raise, lower, currentAmount函數。但不能讀取rent,changeBy函數。

?

Closures在函數編程中的2個重要concepts(不理解?)

  • partial application 局部應用
  • currying 梳理(?)

Currying是一種簡單的創建函數的方法,這種方法會考慮一個函數的參數的局部使用。

簡單來說,一個函數接受另一個函數和多個參數,并返回一個函數及較少的參數。

Partial application搞定了在返回函數中的一個或多個參數。

返回的函數接受了剩下的parameters作為arguments來完成這個函數應用。

partialApplication(targetFunction: Function, ...fixedArgs: Any[]) =>functionWithFewerParams(...remainingArgs: Any[])

?

使用array的普通方法的內部結構來理解這2個概念:

Array.prototype.map()方法

map用來創建一個新的array。 調用一個函數作為參數,這個函數應用到每個array元素上,并返回結果。

var new_array = arr.map(function callback(currentValue[, index[, array]]) {// Return element for new_array }[, thisArg])

?

參數Parameters:

  • callback:函數,用于創建新array的元素,它接受3個參數,第一是必須的:
    • currentValue: 在array中,正在被執行的元素。
    • index:? current element在array 中的索引。
    • array: 調用map方法的數組本身。
  • thisArg: 當執行callback時,作為this本身。

Return value:

一個新的array,每個元素是被callback函數處理過的。

內部結構:

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結構類似,但是,callback函數用來測試每個數組中的元素。如果返回ture則保留這個元素。

?

?


?

Data Structures: Objects and Arrays

相比String, Number, Boolean, Null, Undefined更復雜的數據結構。可以看作是其他數據結構的容器。

一般來說,幾乎everything in JS is an Object. 因此, JS可以看成是對象化編程語言。

在瀏覽器中,一個window加載后,Document對象的一個實例就被創建了。

在這個頁面上的所有things都是作為document object的child。

Document methods是用來對父對象進行相關的操作。

const myObject = {myKey1: 'ObjectValue1',myKey2: 'ObjectValue2',mykeyN: 'ObjectValueN',objectMethod: function() {// Do something on this object } };

?

?

為什么說everything is an Object?

const myMessage = "look at me!"這個數據類型是字符串。

但其實它是由String對象生成的實例instance,通過_proto_屬性,可以調用String中的methods.

String.prototype.toUpperCase.

myMessage.toUpperCase()??

??:

myMessage是String的一個實例,myMessage的_proto_屬性,就是String.prototype。

實例myMessage通過_proto_屬性,調用String中儲存在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

擴展知識點:見博客:原型對象和prototype(https://www.cnblogs.com/chentianwei/p/9675630.html)

?

constructor屬性

還是說上面的例子,String實例myMessage的數據類型是什么:

typeof myOtherMessage //返回 "string"

?

這是如何構建的?使用實例的constructor屬性:

myOtherMessage.constructor //得到,? String() { [native code] }

?

?

由此可知myOtherMessage變量用于存儲一個字符串。它本身是由String構造的實例對象。

everything is object,理解了把!


?

"this" Keyword

詳細看(博客)(或者YDJS對應的章節)
4條rule:

  • default binding
  • implicit binding
  • explicit binding:? 使用call(), apply(),bind()方法明確指定call-site
  • new binding
  • 使用方法:

    先找到call-site,然后檢查符合哪條rule。

    call-site,即一個函數被調用的地點,也可以說一個函數所處的execution context。

    ?

    優先級:

    new > explicit > implicit > default

    ?

    Rule 1: Default (Global) Binding

  • 默認使用全局作用域。
  • 如果在函數中使用'use strict'模式,this的作用域是這個函數的作用域。
  • ?

    Rule 2: Implicit Binding

    根據call-site。根據對象。

    例子:

    var company = {name: 'Baidu',printName() {console.log(this.name)} }var name = 'google'company.printName() // Baidu, 因為printName()函數被company對象調用。var printNameAgain = company.printNameprintNameAgain(); // google, 因為這個函數被全局對象調用。

    ?

    ?

    Rule 3: Explicit Binding

    可以明確指定調用點。

    使用call, apply ,bind方法。傳遞對象作為參數。第一個參數是一個對象,它被傳遞給this關鍵字。

    因此this指向就明確了。

    //根據上例子 printNameAgain.call(company) // Baidu.

    ?

    call(), 可以傳遞string, 數字等作為其他參數。

    apply(), 只能接受一個數組作為第2個參數.

    ?

    bind()最為特殊,它會綁定一個context。然后返回這個函數和調整后的context。

    var printFunc = printNameAgain.bind(company) //printFunc是printNameAgain函數,并綁定company對象, this永遠指向company。 printFunc() // Baidu

    ?

    ?

    Rule 4: Constructor Calls with new

    使用函數構造調用。如new Number()

    注意:

    constructor就是一個函數,和new操作符一起在被調用時運行。和類無關也不實例化類!就是一個標準的函數。

    當一個函數前面有一個new, 會自動做以下事情:

  • a brand new object is created
  • the newly constructed object is?[[Prototype]]-linked,
  • the newly constructed object is set as the?this?binding for that function call
  • unless the function returns its own alternate?object,?the?new-invoked function call will?automatically?return the newly constructed object
  • 第3句:新構建的對象被設置為this, 這個對象和new-invoked函數調用綁定在一起。

    function Company() {this.name = 'baidu' }var b = new Company()//當執行代碼時,會發生: function Company() {// var this = {};this.name = 'Scotch'// return this; 給變量b。 }

    ?

    由此可知:

    第4句:默認情況下,使用new關鍵字的函數,會自動地返回新構建的對象。除非明確指定返回對象。

    ?

    Async Handling

    在異步邏輯時,函數回調可能存在this binding的陷阱。

    因為這些handers往往綁定一個不同的context,讓this的行為產生非期待的結果。

    ?

    Event handing就是一個例子。事件處理器是回調函數。在運行時,當事件被激活,回調函數被執行。

    瀏覽器需要提供和這個event相關的contextual information。它會綁定到回調函數中的this關鍵字。

    ?

    以下代碼,在執行后可以看到this的綁定對象:

    button.addEventListener('click', function() {console.log(this) });

    ?

    ?

    假如你希望產生某個行為:

    var company = {name: 'Scotch',getName: function() {console.log(this.name)} }// This event's handler will throw an error button.addEventListener('click', company.getName)

    ?

    因為瀏覽器提供的contextual info內,不一定有name這個屬性。所以可能會報告?。

    告訴你name property is not existed。

    或者有這個name屬性,但返回的值肯定不是你想要的結果。

    所以需要使用bind()方法,明確指定this的綁定:

    button.addEventListener('click', company.getName.bind(company))

    ?



    ?

    ?

    Basic Deisgn Patterns?

    軟件工程設計,存在大量不同的設計模式。

    JS是一種非傳統的面向對象的編程語言。

    ?

    設計模式(全免介紹不同的JS設計模式)

    (https://www.dofactory.com/javascript/design-patterns)

    ?

    3種設計模式分類:?

    Creational patterns:

    這種模式集中在創建對象。當在一個大型程序種創建對象時,有讓對象變復雜的趨向。通過控制對象的創建,Creational design patterns創造式設計模式可以解決這個問題。

    ?

    Structural patterns:

    這種模式提供了方法,用于管理對象和對象的關系,以及創建class structure。

    其中一種方法是通過使用inheritance繼承, 和composition,從多個小的對象,到創建一個大的對象。

    ?

    Behavioral patterns

    這種模式集中在對象之間的交互上。

    ?

    區別:

    • Creational patterns描述了一段時間。
    • Structural patterns描述了一個或多或少的static structure。
    • 而Behavioral patterns描述了一個process, a flow。

    ?

    ?

    Creational Patterns

    Module模塊

    這種模式常用于軟件開發,這個module pattern可以被看作?Immediately-Invoked-Function-Expression?(IIFE).

    (function() {// code goes here! })();

    ?

    所有module代碼在一個closure內存在。

    Variables通過執行函數傳入value來進口imported, 并返回一個對象來出口exported。

    ?

    這種Modules比單獨的函數使用的方法有優勢:

    它能夠讓你的global namespace 更干凈,更可讀性,也讓你的函數可以importable and exportable.

    一個例子:

    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,雖然現在不再使用它了。

    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

    ?

    這種模式,讓我們構建對象而無需創建這個對象,我們需要做的是指定數據type和對象的content。

    這種模式的關鍵:

    It aims at separating an object’s construction from its representation

    我們無需再設計construction了。只提供內容和數據類型即可。

    ?

    ?$?variable adopts the Builder Pattern in jQuery.

    因此,無需再使用如document.createElement('div')等傳統的創建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

    這種模式:簡單地把一大片邏輯隱藏在一個簡單的函數調用中function call。

    內部的子程序和layers也被隱藏,并通過a facade來使用。

    這種模式讓開發者看不到它的內部結構。開發者也無需關心它。

    例子:

    $(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對Vue實例中 data屬性的追蹤,應該是一個Observer pattern。

    ?

    結論:

    沒有完美的設計模式。各種模式都是為了更好的寫web app。

    相關書籍:

    "Learning JavaScript Design Patterns" by?Addy Osmani?


    ?

    ?

    Callbacks, Promises, and Async

    ?

    函數是First-Class Objects:

    1.函數可以被當作value,分配給變量

    2.可以嵌套函數

    3.可以返回其他函數。

    ?

    Callback Functions?

    當一個函數簡單地接受另一個函數作為參數argument, 這個被當作參數的函數就叫做回調函數。

    使用回調函數是函數編程的核心概念。

    例子:

    setInterval(),每間隔一段time, 調用一次回調函數。

    setInterval(function() {console.log('hello!'); }, 1000);

    var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);

    ?

    例子:

    Array.map(), 把數組中的每個元素,當作回調函數的參數,有多少元素,就執行多少次回調。最后返回一個新的array.

    ?

    Naming Callback functions

    回調函數可以被命名,回調函數可以是異步的。setInterval()中的函數就是異步函數。

    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!

    ?

    當執行introduction()時,greeting函數被當作參數傳入,并在introduction內部執行。

    ?

    回調地獄Callback hell

    function setInfo(name) {address(myAddress) {officeAddress(myOfficeAddress) {telephoneNumber(myTelephoneNumber) {nextOfKin(myNextOfKin) {console.log('done'); //let's begin to close each function! };};};}; }

    ?

    除了不好看外,當變復雜后,傳統的回調函數調用還會出現回調函數調用過早,或者過晚,等等問題

    具體看這篇博客https://www.cnblogs.com/chentianwei/p/9774098.html

    ?

    Promises

    因為Promises封裝了時間依賴狀態the time-dependent state?---等待滿足或拒絕這個潛在的value--從外部,因此Promises可以被composed(combined, 比如x和y做加法運算)

    一旦一個Promise被解決,它就是一個不變的值,如果需要可以多次被observed。

    ?

    Promises是一個方便的可重復的機制用于封裝和組織furture value。

    ?

    Promise有3個狀態:

    • Pending: 初始狀態,在一個操作開始前的狀態.
    • Fulfilled: 當指定的操作被完成后的狀態。
    • Rejected: 操作未完成,或者拋出一個?值
    const promise = new Promise(function(resolve, reject) {//相關代碼//resole, reject是2個Promise的內置函數。處理不同的結果。 })

    ?

    ?

    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的值是一個Promise對象,其中:

    屬性[[PromiseStatus]]的值是"resolved",

    (如果weather = false, 最后date中的屬性[[PromiseStatus]]的值是"rejected"

    屬性[[PromiseValue]]的值是一個對象.

    ?

    使用Promise對象

    當得到promise對象后,可以使用then(), catch(),調用回調函數,

    對promise對象進行進一步操作,并返回一個新的promise對象。

    當Promise對象中的屬性[[PromiseStatus]]的值:

    • resolve,會調用then()
    • rejecte,? ?會調用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'

    ?

    我們使用?創建的promise對象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()

    ?

    得到結果:

    We are going on a date! // console.log(done) 在控制臺界面顯示done參數。 {name: "Cubana Restaurant", location: "55th Street", table: 5}location: "55th Street"name: "Cubana Restaurant"table: 5__proto__: Object

    ?

    由此可見,.then()中,給回調函數的參數done,其實就是promise對象date中的[[PromiseValue]]

    而date是執行resolve(dateDetails)函數后返回的結果。

    因此,.then()接收的參數就是promise對象date的resolve()的值。

    而,? .catch()接收的參數是promise對象date的reject()的值。

    ?

    ??Promises是異步的。Promises在函數中被放置在一個小的工作棧內,并在其他同步操作完成后運行run。

    ?

    Chaining Promises

    如果基于the result of preceding promises來執行2個以上的異步操作時,需要chain promises。

    還是使用上面的代碼:

    //創建一個新的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對象date了,

    這是因為執行order函數會返回一個新的promise對象。

    const myDate = function() {date.then(order) //傳入回調函數order.then(function(done) { //...}).catch(function(err) { console.log(err.message)}) }
    myDate()

    ?


    ?

    ?

    Async and Await?(點擊查看文檔說明)

    EMS2017中的新語法糖。僅僅讓寫promise更容易。但老的瀏覽器不支持。

    在一個函數前加上async關鍵字,這個函數會返回一個promise對象。

    如果函數返回的值是true, promise中的[[PromiseState]]的值將是'resolved'。

    但是函數返回的值是false, async function會拋出?,promise中的[[PromiseState]]的值將是'rejected'

    async function myRide() {return '2017' }

    ?等同于

    function yourRide() {return Promise.resolve('2017') }

    如果函數返回false:

    function foo() {return Promise.reject(25) } // is equal to async function() {throw 25 }

    ?

    Await

    和async function配套使用的關鍵字(語法糖)

    用于保證所有在async function中返回的promises是同步的。

    await等待其他promise執行完成,然后在執行后續代碼。

    ?

    async在返回一個promise前是等待狀態。

    await在調用一個promise前是等待狀態。

    ?

    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的核心版本,每個js developer必須掌握的。

  • Promises??
  • Variable Declaration?
  • Multi-line Strings? 使用反引號``
  • Destructuring Assignment??
  • Object Literals??
  • Arrow Function??
  • Default Parameters??
  • Template Literals? 在反引號內,使用${ //... }
  • Classes??
  • Modules??
  • ?

    ?

    Promises in ES6

    在promise出現之前,開發者不得不大量使用callbacks。

    setTimeout, XMLHttpRequest是基本的基于瀏覽器的異步函數的回調。

    setTimeout(function() {console.log('Cool!') }, 1000);

    ?

    使用Promise:

    let lunchTime = new Promise(function(eat, skip) {setTimeout(eat, 1000) }).then(function() {console.log('lunch time!') })

    ?

    使用ES6箭頭函數更方便:

    let lunchTime = new Promise((eat, skip) => setTimeout(eat, 1000)).then(() => console.log('Lunch Time!'))

    ?

    隨著應用開發,代碼的邏輯會更加的復雜,promise可以更好的處理這些邏輯:

    //聲明的變量儲存一個函數 var lunchTimeDelay1000 = () => new Promise((eat, skip) => { setTimeout(eat, 1000) })//使用2次.then()執行不同的邏輯: //第一個then()內,返回lunchTimeDelay1000的執行,即返回原promise對象,以便執行下一個邏輯 lunchTimeDelay1000().then(function() {console.log('Lunch Time!');return lunchTimeDelay1000();}).then(function() {console.log('Good Food!');});

    如此,代碼非常容易理解,運行代碼,等待1秒,然后繼續運行代碼,再等待,并可以再運行更多代碼。

    ?

    Variable Declaration in ES6

    新版使用let, const, var的使用范圍被減少。

    ?

    Multi Line Strings in ES6

    傳統字符串,換行用\n, 叫做backslash

    ES6,可以使用backticks,反引號 ``, 然后直接回車換行。

    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的另一個功能,可以插入變量, 使用${}

    ?

    Destructuring Assignment in ES6? 拆解賦值

    見對象x:

    var x = {fish: 1, meat: 2} fish = x.fish //1 meat = x.meat // 2//使用ES6 var {fish, meat} = x

    ?

    ?注意??,變量fish, meat,這2個identifier,在x中有對應的屬性fish和meat。如果沒有,則無法賦值。

    ?

    array也可以拆分分配

    具體見之前的博客:https://www.cnblogs.com/chentianwei/p/10153866.html

    例子:

    for..of顯示一個array的內容

    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的一些簡化和改進:

    • 在object construction上建立prototype (未理解用途)
    • 簡化方法聲明
    • Make super calls? (未理解用途)
    • Computed property names

    例子:典型的ES5對象字面量,內有一些方法和屬性。這里使用了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, 引用一個函數,只要名字相同就可以簡化方法聲明。

    super關鍵字

    用于存取和調用對象的父對象上的函數。

    super.prop, super[expr]表達式可以通過任何在classes和object literals中的方法定義的驗證。

    super([arguments]); // calls the parent constructor. super.functionOnParent([arguments]);

    ['valueOf_' + getAccounts().join('_')]: 可以使用通過計算得到的屬性名字。

    ?

    Arrow Functions in ES6

    箭頭函數中的this.指向調用函數的對象。

    const stringLowerCase = function() {this.string = this.string.toLowerCase();return () => console.log(this.string); }stringLowerCase.call({string: 'JAVASCRIPT' })()

    ?

    注意,只有一行的代碼的時候,使用箭頭函數,可以省略return

    let sayHello = () => 'hello'

    ?

    ?

    Default Parameters in ES6

    小的功能的改進

    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反引號內使用dollar sign and curly braces: ${ //... }

    ?

    Nesting templates

    可以在一個template內使用``, 即嵌套模版。

    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 繼承上的語法糖。

    簡化了傳統的寫法。可以像傳統的對象類一樣,使用class句法。但核心未變(prototype-based inheritance)。

    ?

    定義classes

    classes只不過是特殊的函數。

    就像可以定義函數表達式和函數聲明。class句法也有2個組件:

    • ?class expressions:是在ES6中定義一個類的一個方法,還可以類聲明。
    • ?class declarations:? 用一個名字來創建一個新的class。用到prototype-based inheritance.?
    //class expression var MyClass = class [className] [extends] {// class body }//class declaration class name [extends] {// class body }

    ?

    ?

    class expressions

    和class statement(declaration)有類似的句法結構。但是,

  • 可以omit name,漏掉name
  • 可re-define/re-declare classes, 并不會拋出?。(和ruby中定義類一樣)
  • 使用typeof檢查它的類型,永遠是function類型。
  • 如果一個類表達式使用一個name,這個name會存在類表達式的body內。

    class declarations

    只能定義一次,之后不能再修改。

    注意,類聲明不能被hoisting。所以必須先聲明,再使用。否則會報錯?。

    ?

    Class body and method definitions

    所有的類成員都寫在body內,即{ }內。如methods or constructor。

    Constructor

    這是一個特殊的方法,用于創建和初始化initializing一個對象。

    一個類內只能有一個constructor方法。否則拋出?。

    Prototype methods

    從ES6開始,關于對象初始化的方法定義的簡單句法被引進。

    var obj = {property(params...) {},*generator(params...) {},async property(params...) {},async *generator(params...) {},//使用計算的keys [property](params...) {}, *generator(params...) {},async property(params...) {},//使用比較句法 getter/setter, 定義一個非函數屬性。 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

    實例屬性必須定義在class methods內。

    class Rectangle {constructor(height, width) { this.height = height;this.width = width;} }

    ?

    Static methods

    static關鍵字定義了靜態方法。調用靜態方法無需實例化類,也不能被類實例調用(就是類方法)

    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關鍵字

    ES6增加了extends關鍵字來創建一個類的子類。

    例子:

    本例子,在子類的constructor內使用了super關鍵字

    //使用了ES6的句法:
    class Animal { constructor(name) {
    this.name = name;}speak() {console.log(this.name + ' makes a noise.');} } //如果一個constructor在子類中存在,它需要調用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函數,也可以。但使用的化,必須配合super()。

    ?

    另外,可以使用傳統的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.

    ?

    再次強調,JavaScript的類是prototype-based的

    Dog.prototype
    //Animal {constructor: ?, speak: ?}

    ?

    ?

    類classes 不能extend標準對象(non-constructible)。

    因此,如果你想要繼承自一個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關鍵字可以調用父類的方法

    除了上文提到的在子類的constructor中使用super(params...),

    還可以在子類中的方法中使用super.

    例子:

    class Lion extends Cat {speak() {super.speak();console.log(`${this.name} roars.`);} }

    ?

    Modules in ES6

    在ES6之前,JS不支持modules。現在有了import和export操作符。

    在ES5, 常見使用<script>標簽和IIFE(即使用()();),或者AMD之類的庫。實現類似功能。

    ?

    流行的寫法:

    //module.js export var port = 3000 export function getCar(model) {...}//main.js import {port, getCar} from 'module';

    可選的,使用as關鍵字把引進的存入一個變量:

    import * as service from 'module' console.log(service.port) //3000

    語法:

    //輸出變量name1, name2 export { name1, nam2, } //使用別名 export { var1 as name1 } //聲明+賦值,然后輸出。(如果不賦值,則值默認為undefined) export let name1 = 100 //輸出函數, class都可以。 export function Name() {...}//輸出默認的表達式, 函數,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在線編輯器,可以看轉化格式。 exports.s = s
    //或者
    module.exports = s

    ?

    ?

    CommonJS規范

    這種模塊加載機制被稱為CommonJS規范。在這個規范下,每個.js文件都是一個模塊,它們內部各自使用的變量名和函數名都互不沖突,例如,hello.js和main.js都申明了全局變量var s = 'xxx',但互不影響。

    一個模塊想要對外暴露變量(函數也是變量),可以用

    module.exports = variable;,

    一個模塊要引用其他模塊暴露的變量,用

    var ref = require('module_name');

    ?

    深入了解模塊原理

    JS語言本書并沒有一種機制保證不同的模塊可以使用相同的變量名。相同的變量名就會沖突!

    但,實現模塊的奧妙在于: Closures!

    把一段js代碼用一個函數包裹起來,這段代碼的"全局"變量,就成了函數內的局部變量了!

    ?

    首先了解一下, node.js的模塊加載原理:如何讓變量名不沖突。

    //hello.js var s = 'Hello'; var name = 'world';console.log(s + ' ' + name + '!');//Node.js加載hello.js, 會使用IIFE (function () {// 讀取的hello.js代碼:var s = 'Hello';var name = 'world';console.log(s + ' ' + name + '!');// hello.js代碼結束 })();

    ?

    這樣,Node.js加載其他模塊時,變量s都是局部的了。

    ?

    再了解module.exports的實現:

    Node先準備一個對象module,

    // 準備module對象: var module = {id: 'hello',exports: {} };

    ?

    然后:

    module.exports = variables //這是我們要輸出的變量var load = function(module) {return module.exports; } var exported = load(module) //得到要輸出的內容。
    //Node把module變量保存到某個地方 save(module, exported)

    ?

    由于Node保存了所有導入的module,當我們使用require()獲取module時,Node找到對應的module,把這個module的exports變量返回。 這樣另一個模塊就順利拿到了模塊的輸出:

    var greet = require('./hello');

    ?

    ?

    ES6之后,直接使用關鍵字export和import即可!

    ?

    getter?

    get syntax綁定一個對象的屬性到一個函數,當屬性被調用(查詢)時,執行這個函數。

    //Syntax {get prop() { ... } } {get [expression]() { ... } }

    ?

    介紹:

    有時候,讓一個屬性能夠返回動態的可計算的值,是非常方便的,

    或者,你可能想要反應這個內部變量的status,卻無需使用明確的方法來調用。

    在JavaScript,可以通過使用getter來完成。

    ??,一個屬性,不能同時既綁定一個函數,又有一個明確的值。

    //以下都是?的
    //屬性x,不能有多個函數綁定。
    { get x() { }, get x() { } }
    //屬性x, 不能同時既有明確的值,又有函數生成的計算后返回的值。 { x: ..., get x() { } }

    ?

    ??,使用getter的屬性,只能有0個或1個參數。

    ??, delete 操作符,可以刪除一個getter。

    例子:

    在對象初始化時,定義一個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操作符號,刪除一個getter
    delete
    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

    默認的getters,是懶惰的:

    Getters可以讓你定義一個對象的屬性,但是如果你不存取(使用)它,這個屬性的值不會被計算。(類似函數)

    ?

    setter

    set句法綁定一個對象的屬性到一個函數,但想要用這個屬性改變什么,調用這個函數。

    ?

    {set prop(val) {...}} {set [expression](val) {} }

    ?

    當想要改變一個指定的屬性時,調用這個函數。

    setter和getter一起使用,創建一個偽屬性的類型。a type of pseudo-property。

    ??

    必須有一個明確的參數。

    禁止:(?{ set x(v) { }, set x(v) { } }?and?{ x: ..., set x(v) { } }

    setter可以被delete方法刪除。

    ?

    例子

    在對象初始化時定義一個setter。

    var language = {set current(name) {this.log.push(name)},log: [] }language.current = 'En' //"En" language.current = 'Fa' //"Fa" language.log //(2)?["En", "Fa"]

    ?

    ??,因為沒有使用getter,所以language.current會得到undefined。

    ?

    如果要給已經存在的對象,添加一個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也可以使用計算屬性名字。

    ?

    結論

    不是所有瀏覽器都支持ES6的所有功能。因此需要使用編譯器如Babel.?

    Babel可以是Webpack的一個插件。也可以單獨作為tool使用。

    關于為什么要使用編譯器:見這篇文章:

    https://scotch.io/tutorials/javascript-transpilers-what-they-are-why-we-need-them

    ?

    轉載于:https://www.cnblogs.com/chentianwei/p/10197813.html

    總結

    以上是生活随笔為你收集整理的JavaScript的几个概念简单理解(深入解释见You Don't know JavaScript这本书)的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。