建議優(yōu)先掌握:
-
instanceof
- 考察對(duì)原型鏈的理解
-
new
- 對(duì)創(chuàng)建對(duì)象實(shí)例過程的理解
-
call/apply/bind
- 對(duì)this指向的理解
- 手寫promise - 對(duì)異步的理解
- 手寫原生ajax - 對(duì)ajax原理和http請(qǐng)求方式的理解遣鼓,重點(diǎn)是get和post請(qǐng)求的實(shí)現(xiàn)
實(shí)現(xiàn)instanceOf
- 思路:
- 步驟1:先取得當(dāng)前類的原型,當(dāng)前實(shí)例對(duì)象的原型鏈
- 步驟2:一直循環(huán)(執(zhí)行原型鏈的查找機(jī)制)
- 取得當(dāng)前實(shí)例對(duì)象原型鏈的原型鏈(proto = proto.proto,沿著原型鏈一直向上查找)
- 如果 當(dāng)前實(shí)例的原型鏈proto上找到了當(dāng)前類的原型prototype怠蹂,則返回 true
- 如果 一直找到Object.prototype.proto == null抗愁,Object的基類(null)上面都沒找到锐朴,則返回 false
// 實(shí)例.__ptoto__ === 類.prototype
function myInstanceof(example, classFunc) {
let proto = Object.getPrototypeOf(example); //返回指定對(duì)象的原型
while(true) {
if(proto == null) return false;
// 在當(dāng)前實(shí)例對(duì)象的原型鏈上殷费,找到了當(dāng)前類
if(proto == classFunc.prototype) return true;
// 沿著原型鏈__ptoto__一層一層向上查
proto = Object.getPrototypeof(proto); // 等于proto.__ptoto__
}
}
new操作符做了這些事:
- 創(chuàng)建一個(gè)全新的對(duì)象
- 這個(gè)對(duì)象的proto要指向構(gòu)造函數(shù)的原型prototype
- 執(zhí)行構(gòu)造函數(shù)追驴,使用 call/apply 改變 this 的指向
- 返回值為object類型則作為new方法的返回值返回眉枕,否則返回上述全新對(duì)象
function myNew(fn, ...args) {
let instance = Object.create(fn.prototype); //創(chuàng)建一個(gè)新對(duì)象恶复,使用現(xiàn)有的對(duì)象來提供新創(chuàng)建的對(duì)象的__proto__怜森。
let res = fn.apply(instance, args); // 改變this指向
// 確保返回的是一個(gè)對(duì)象(萬一fn不是構(gòu)造函數(shù))
return typeof res === 'object' ? res: instance;
}
實(shí)現(xiàn)一個(gè)call方法
Function.prototype.myCall = function (context = window) {
context .func = this;
let args = Array.from(arguments).slice(1); //從一個(gè)類似數(shù)組或可迭代對(duì)象創(chuàng)建一個(gè)新的,淺拷貝的數(shù)組實(shí)例谤牡。
let res = args.length > 1 ? context.func(...args) : context.func();
delete context.func;
return res;
}
實(shí)現(xiàn)apply方法
Function.prototype.myApply = function (context = window) {
context.func = this;
let res = arguments[1] ? context.func(...argumnets[1]) : context.func();
delete context.func;
return res;
}
實(shí)現(xiàn)一個(gè)bind方法
Function.prototype.myBind = function (context) {
let cext = JSON.parse(JSON.stringify(context)) || window;
cext .func = this;
let args = Array.from(argumnets).slice(1);
return function () {
let allArgs= args .concat(Array.from(arguments));
return allArgs.length ? cext.func(...allArgs) : cext.func();
}
}
實(shí)現(xiàn)一個(gè)Promise
class myPromise {
constructor (fn) {
this.status = 'pending';
this.value = undefined;
this.reason = undefined;
this.onFulfilled = [];
this.onRejected = [];
let resolve = value => {
if(this.status === 'pending') {
this.status = 'fulfilled';
this.value = value;
this.onFulfilled.forEach(fn => fn(value));
}
}
let reject = value => {
if(this.status === 'pending') {
this.status = 'rejected';
this.reason = value;
this.onRejected.forEach(fn => fn(value))
}
}
try {
fn(resolve,reject);
} catch (e) {
reject(e)
}
}
then (onFulfilled,onRejected) {
if(this.status === 'fulfilled') {
typeof onFulfilled === 'function' && onFulfilled(this.value);
}
if(this.staus === 'rejected') {
typeof onRejected === 'function' && onRejected(this.reason);
}
if(this.status === 'pending') {
typeof onFulfilled === 'function' && this.onFulfilled.push(this.value);
typeof onRejected === 'function' && this.onRejected.push(this.reason);
}
}
}
let p = new myPromise ((resolve,reject) => {
console.log('我是promise的同步代碼');
//異步任務(wù)
$.ajax({
url:'data.json',
success:function (data) {
resolve(data)
},
error:function (err) {
reject(err);
}
})
})
p.then((res) => {
console.log(res);
})
手寫原生AJAX
- 步驟
- 創(chuàng)建 XMLHttpRequest 實(shí)例
- 發(fā)出 HTTP 請(qǐng)求
- 服務(wù)器返回 XML 格式的字符串
- JS 解析 XML副硅,并更新局部頁面
- 不過隨著歷史進(jìn)程的推進(jìn),XML 已經(jīng)被淘汰拓哟,取而代之的是 JSON想许。
- 了解了屬性和方法之后,根據(jù) AJAX 的步驟断序,手寫最簡單的 GET 請(qǐng)求流纹。
function ajax () {
let xml = new XMLHttpRequest();
xml.open('get','https://www.google.com',true);
xml.onreadystatechange = () => {
if(xml.readystate === 4) {
if(xml.status > 200 && xml.status < 300 && xml.status = 304){
alert(xml.responseText);
}else {
alert('Error' + xml.status);
}
}
}
xml.send();
}
promise實(shí)現(xiàn)AJAX:
- 返回一個(gè)新的Promise實(shí)例
- 創(chuàng)建XMLHttpRequest異步對(duì)象
- 調(diào)用open方法,打開url违诗,與服務(wù)器建立鏈接(發(fā)送前的一些處理)
- 監(jiān)聽Ajax狀態(tài)信息
- 如果xhr.readyState == 4(表示服務(wù)器響應(yīng)完成漱凝,可以獲取使用服務(wù)器的響應(yīng)了)
- xhr.status == 200,返回resolve狀態(tài)
- xhr.status == 404诸迟,返回reject狀態(tài)
- xhr.readyState !== 4茸炒,把請(qǐng)求主體的信息基于send發(fā)送給服務(wù)器
function myAjax (url,method) {
return new Promise((resovle,reject) => {
const xhr = new XMLHttpRequest();
xhr.open(url,method,true);
xhr.onReadystatechange = function () {
if(xhr.readyState === 4 ){
if(xhr.status >200 && xhr.status <300 && xhr.status ===304 ){
resolve(xhr.responseText);
}else if(xhr.status === 404){
reject(new Error('404'));
}
}else{
reject('請(qǐng)求數(shù)據(jù)失敗阵苇!');
}
}
xhr.send(null)
})
}