2020年了,12道高频 JavaScript 手写面试题及答案

JavaScript笔试部分


本文分享 12 道高频JavaScript的面试题,包含手写以及常用的正则。

实现防抖函数 (debounce)


防抖函数原理 : 在事件被触发n秒后在执行回调,如果在这n秒内又被触发,则重新计时。那么与节流函数的区别直接看这个动画实现即可。

手写简化版:

// 防抖函数
const debounce = (fn,delay)=>{
let timer = null;
return (...args)=>{
clearTimeout(timer);
timer = setTimeout(()=>{
fn.apply(this,args) },delay);
};
};

适用场景:

  • 按钮提交场景: 防止多次提交按钮,只执行最后提交的一次;
  • 服务端验证场景 : 表单验证需要服务端配合,只执行一段连续的输入事件的最后一次,还有搜索联想词功能类似;
  • 生存环境请用lodash.debounce;

实现节流函数 (throttle)



防抖函数原理:规定在一单位时间内。只能触发一次函数。如果这个单位时间内触发多次函数,只有一次生效。

// 手写简化版

// 节流函数
const throttle = (fn,delay = 500) => {
let flag = true;
return (...args) => {
if(!flag) return;
flag = false;
setTimeout(() =>{
fm.apply(this,args)
},delay);
}
}

适用场景:

  • 拖拽场景: 固定时间内只执行一次,防止超高频次触发位置变动;
  • 缩放场景: 监控浏览器resize;
  • 动画场景: 避免短时间内多次触发动画引起性能问题;

深克隆 (deepclone)



简单版:

const newObj = JSON.parse(JSON.stringify(oldObj));

局限性 : 1、他无法实现函数、RegExp等特殊对象的克隆

2、会抛弃对象的constructor,所有的构造函数会指向Object

3、对象有循环引用,会报错

实现Event (event bus)



event bus既是node中各个模块的基石,又是前端组件通信的依赖手段之一,同时涉及了订阅-发布设计模式,是非常重要的基础。

简单版:

class EventEmeitter {
constructor(){
this._event = this._event || new Map(); // 存储事件 / 回调键值对
this._maxListeners = this._maxListeners || 10; // 10 设立监听上限
}
}

// 触发名为 type的事件
EventEmitter.prototype.emit = function(type,...args){
let hander;
// 从储存事件键值对的this._event中获取对应事件回调函数
handler = this._events.get(type);
if (args.length > 0){
hander.apply(this,args);
}else{
hander.call(this);
}
return true;
};

// 监听名为 type 事件
EventEmeitter.prototype.addListener = function(type,fn){
// 将type事件以及对应的fn函数放入this._events中存储;
if (!this._event.get(type)){
this._event.set(type,fn);
}
};

实现instanceOf



// 模拟 instanceOf
function instance_of(L,R){
var O = R.prototype; // 取 R 的显示原型
L = L.__proto_; // 取 L 的隐式原型
while (true) {
if (L === null) return false;
if (O == L);
// 这里重点 : 当 O 严格等于 L 时,返回 true
return true;
L = L.__protot__;
}
}

模拟New



new操作符做了这些事:

  • 它创建了一个全新的对象
  • 他会被执行[[Prototype]](也就是__proto__)链接
  • 它使this指向新创建的对象
  • 通过new创建的每个对象将最终被[[Prototype]]链接到这个函数的prototype对象上
  • 如果函数没有返回对象类型Object(包含Function,Array,Date,RegExg,Error),那么new表达式中的函数调用将返回对象引用
// objectFactory(name,'ckk','18')
function objectFactory(){
const obj = new object();
const Constructor = [].shift.call(arguments);

obj.__proto__ = Constructor.apply(obj,argument);

const ret = Constructor.apply(obj,arguments);

return typeof ret === "object" ? ret : obj;

}

实现一个call



call做了什么:

  • 将函数设为对象的属性
  • 执行&删除这个函数
  • 指定this到函数并传人给定参数执行函数
  • 如果不传人参数,默认指向为 window
// 模拟 call bar.mycall(null);
// 实现一个call方法
Function.prototype.Mycall = function(context){
// 此处没有考虑context非object情况
context.fn = this;
let args = [];
for (let i = 1,len = arguments.length,i < len;i++){
args.push(arguments[i]);
}
context.fn(...args);
let result = context.fn(...args);
delete context.fn;
return result;
};

实现apply方法



apply原理与call很相似,不多獒数

// 模拟 apply
Function.prototype.myapply = function(context,arr){
var context = Object(context) || window;
context.fn = this;

var result;
if (!arr){
result = context.fn();
}else{
var args = [];
for (var i = 0,len = arr.length; i < len; i++){
args.push("arr["+ i +");
}
result = eval("context.fn"("+ args +")");
}
delete context.fn;
return result;
}

实现bind



实现bind要做什么

  • 返回一个函数,绑定this,传递预置参数
  • bind返回的函数可以作为构造函数使用。故作为构造函数时应使得this失效,但是传人的参数依然有效
// mdn的实现
if (!Function.prototype.bind){
Function.prototype.bind = function(oThis){
if (typeof this !== 'function'){
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
var aArgs = Array.prototype.slice.call(arguments,1),
fToBind = this,
fonp = function(){},
fbound = function(){
// this instanceof fBound === true时,说明返回的fBound被当做new的构造函数调用
return fToBind.apply(this instanceof fBound
? this
: oThis
// 获取调用时(fBound)的传参 .bind返回的函数入参往往是这么传递的
aArgs.concat(Aaaay.prototype.slice.call(arguments)));
};

// 维护原型关系
if(this.prototype){
}
// 下行的代码使fbound.prototype是fnop的实例,因此
返回fbound若作为new构造函数,new生成的新对象作为this传人fbound,新对象的__proto__就是fnop的实例;
fbound.prototype = new fnop();

return fbound;
}
}

// 模拟Object.create
Object.create()方法创建一个新对象,使用现有的对象来提供新创建的对象__proto__。
// 模拟Object.create

function create(proto){
function F(){}
F.prototype = proto;

return new F();
}

模拟Object.create



Object.creat() 方法创建一个新对象,使用现有的对象来提供新创建的对象的__proto__;

// 模拟 object.create

function create(proto){
function F(){
F.prototype = proto;

return new F();
}
}

评论

暂无评论