實現:json
function myNew() { // 1.建立空對象 let obj = {} let constructor = [...arguments][0] let params = [...arguments].slice(1) // 2.空對象的原型指向構造函數的原型 obj.__proto__ = constructor.prototype // 3.執行構造函數的代碼 var ret = constructor.apply(obj, params) // 4.判斷返回值類型: // 若是是基本值類型,則返回的建立的'空對象' // 若是是引用類型,則返回這個引用類型的對象 var flag = ret && ret instanceof Object return flag ? ret : obj } // test function A(name) { this.name = name } var a1 = myNew(A, 'Lee') var a2 = new A('Lee') console.log(a1, a2)
AJAX 包括如下幾個步驟promise
通常實現:服務器
const SERVER_URL = '/server' let xhr = new XMLHttpRequest() // 建立 Http 請求 第三個參數爲async,指定請求是否爲異步方式,默認爲 true。 xhr.open('GET', SERVER_URL, true) // 設置請求頭信息 xhr.responseType = 'json' xhr.setRequestHeader('Accept', 'application/json') // 設置狀態監聽函數 xhr.onreadystatechange = function () { if (this.readyState !== 4) return // 當請求成功時 if (this.status === 200) { handle(this.responseText) } else { console.error(this.statusText) } } // 設置請求失敗時的監聽函數 xhr.onerror = function () { console.error(this.statusText) } // 發送 Http 請求 xhr.send(null)
promise 封裝實現:app
function getJSON(url) { // 返回一個 promise 對象 return new Promise(function (resolve, reject) { let xhr = new XMLHttpRequest() // 新建一個 http 請求, 第三個參數爲async,指定請求是否爲異步方式,默認爲 true。 xhr.open('GET', url, true) // 設置狀態的監聽函數 xhr.onreadystatechange = function () { /*0: 請求未初始化 1: 服務器鏈接已創建 2: 請求已接收 3: 請求處理中 4: 請求已完成,且響應已就緒*/ if (this.readyState !== 4) return // 當請求成功或失敗時,改變 promise 的狀態 /*200: "OK" 404: 未找到頁面*/ if (this.status === 200) { resolve(this.responseText) } else { reject(new Error(this.statusText)) } } // 設置響應的數據類型 xhr.responseType = 'json' // 設置請求頭信息 xhr.setRequestHeader('Accept', 'application/json') // 發送 http 請求 xhr.send(null) }) }