国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

20道JS原理題助你面試一臂之力(必看)

2024-05-06 15:36:44
字體:
供稿:網(wǎng)友

前言

本文針對目前常見的面試題,僅提供了相應的核心原理及思路,部分邊界細節(jié)未處理。后續(xù)會持續(xù)更新,希望對你有所幫助。

1. 實現(xiàn)一個call函數(shù)

// 思路:將要改變this指向的方法掛到目標this上執(zhí)行并返回Function.prototype.mycall = function (context) { if (typeof this !== 'function') { throw new TypeError('not funciton') } context = context || window context.fn = this let arg = [...arguments].slice(1) let result = context.fn(...arg) delete context.fn return result} 

2. 實現(xiàn)一個apply函數(shù)

// 思路:將要改變this指向的方法掛到目標this上執(zhí)行并返回Function.prototype.myapply = function (context) { if (typeof this !== 'function') { throw new TypeError('not funciton') } context = context || window context.fn = this let result if (arguments[1]) { result = context.fn(...arguments[1]) } else { result = context.fn() } delete context.fn return result}

3. 實現(xiàn)一個bind函數(shù)

// 思路:類似call,但返回的是函數(shù)Function.prototype.mybind = function (context) { if (typeof this !== 'function') { throw new TypeError('Error') } let _this = this let arg = [...arguments].slice(1) return function F() { // 處理函數(shù)使用new的情況 if (this instanceof F) {  return new _this(...arg, ...arguments) } else {  return _this.apply(context, arg.concat(...arguments)) } }}

4. instanceof的原理

// 思路:右邊變量的原型存在于左邊變量的原型鏈上function instanceOf(left, right) { let leftValue = left.__proto__ let rightValue = right.prototype while (true) { if (leftValue === null) {  return false } if (leftValue === rightValue) {  return true } leftValue = leftValue.__proto__ }}

5. Object.create的基本實現(xiàn)原理

// 思路:將傳入的對象作為原型function create(obj) { function F() {} F.prototype = obj return new F()

6. new本質(zhì)

function myNew (fun) { return function () { // 創(chuàng)建一個新對象且將其隱式原型指向構造函數(shù)原型 let obj = {  __proto__ : fun.prototype } // 執(zhí)行構造函數(shù) fun.call(obj, ...arguments) // 返回該對象 return obj }}function person(name, age) { this.name = name this.age = age}let obj = myNew(person)('chen', 18) // {name: "chen", age: 18}

7. 實現(xiàn)一個基本的Promise

// 未添加異步處理等其他邊界情況// ①自動執(zhí)行函數(shù),②三個狀態(tài),③thenclass Promise { constructor (fn) { // 三個狀態(tài) this.state = 'pending' this.value = undefined this.reason = undefined let resolve = value => {  if (this.state === 'pending') {  this.state = 'fulfilled'  this.value = value  } } let reject = value => {  if (this.state === 'pending') {  this.state = 'rejected'  this.reason = value  } } // 自動執(zhí)行函數(shù) try {  fn(resolve, reject) } catch (e) {  reject(e) } } // then then(onFulfilled, onRejected) { switch (this.state) {  case 'fulfilled':  onFulfilled()  break  case 'rejected':  onRejected()  break  default: } }}            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 海伦市| 霸州市| 琼海市| 新巴尔虎左旗| 城口县| 海安县| 乌拉特后旗| 琼结县| 吉安县| 平罗县| 德格县| 南木林县| 麻城市| 桃江县| 郑州市| 贡嘎县| 沙洋县| 安庆市| 博客| 东乌| 松滋市| 镇坪县| 天台县| 炉霍县| 舟山市| 洛扎县| 剑川县| 安国市| 额尔古纳市| 澄迈县| 开化县| 巴里| 台湾省| 凉城县| 杭锦旗| 富源县| 邢台县| 天津市| 明水县| 建平县| 仁布县|