前言
本文针对目前常见的面试题,仅提供了相应的核心原理及思路,部分边界细节未处理。后续会持续更新,希望对你有所帮助。
1. 实现一个call函数
// 思路:将要改变this指向的方法挂到目标this上执行并返回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. 实现一个apply函数
// 思路:将要改变this指向的方法挂到目标this上执行并返回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. 实现一个bind函数
// 思路:类似call,但返回的是函数Function.prototype.mybind = function (context) { if (typeof this !== 'function') { throw new TypeError('Error') } let _this = this let arg = [...arguments].slice(1) return function F() { // 处理函数使用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的基本实现原理
// 思路:将传入的对象作为原型function create(obj) { function F() {} F.prototype = obj return new F()
6. new本质
function myNew (fun) { return function () { // 创建一个新对象且将其隐式原型指向构造函数原型 let obj = { __proto__ : fun.prototype } // 执行构造函数 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. 实现一个基本的Promise
// 未添加异步处理等其他边界情况// ①自动执行函数,②三个状态,③thenclass Promise { constructor (fn) { // 三个状态 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 } } // 自动执行函数 try { fn(resolve, reject) } catch (e) { reject(e) } } // then then(onFulfilled, onRejected) { switch (this.state) { case 'fulfilled': onFulfilled() break case 'rejected': onRejected() break default: } }}
新闻热点
疑难解答
图片精选