面试整理——手写系列
前言
面试中大概率会出现手写代码的情况,但是对我来说,面试的情况下完成一个完善的手写是比较困难的,所以本篇文章每个手写都会有面试版和完善版两个版本,面试版一般是争取用最少代码完成主要功能以及主要知识点的覆盖,完善版就是扣一些细节(细节可能也有很多)多一些一些特殊情况和边界条件的考虑
手写 new 操作符
面试版
const _new = (fn,...args) => {
const newObj = Object.create(fn.prototype)
fn.call(newObj, ...args)
return newObj
}
完善版
const _new = (fn,...args) => {
const newObj = Object.create(fn.prototype)
const returnVal = fn.call(newObj, ...args)
return returnVal instanceof Object ? returnVal : newObj
}
测试
function Foo(x,y){
this.name = x
this.age = y
}
const obj1 = _new(Foo,'小明',18)
const obj2 = new Foo('小明',18)
console.log(obj1,obj2)
手写 call 方法
面试版
Function.prototype.myCall = function(thisArg,...args){
thisArg = thisArg ?? window;
thisArg.fn = this // this === Function.prototype
const result = thisArg.fn(...args)
delete thisArg.fn;
return result
}
完善版
Function.prototype.myCall = function (thisArg, ...args) {
thisArg = thisArg ?? window;
thisArg = Object(thisArg);
const fn = Symbol();
thisArg[fn] = this;
const result = thisArg[fn](...args);
delete thisArg[fn];
return result;
};
测试
const obj = {
a: 2,
fun: function (x) {
console.log(x);
return this.a;
},
};
const cObj = {
a: 200,
};
console.log(obj.fun(1));
console.log(obj.fun.call(cObj, 100));
console.log(obj.fun.myCall(cObj, 100));