前端面试手写题
整理前端面试常见的手写题,面试出现概率极高,建议每个都过自己过一遍,加深印象。
你可以 watch 一下这个 GitHub 仓库,会持续收集、整理和维护。
实现 bind()
Function.prototype.MyBind = function (context, ...args) {
let self = this;
return function() {
return self.apply(context, args);
}
}
// test
let a = {
name: 'jack'}
let test = function() {
console.log(this.name); // jack
}
let rs = test.MyBind(a);
rs();
实现 apply()
Function.prototype.myApply = function (context, args) {
context.fn = this;
let res;
if (!args){
res = context.fn();
} else {
res = context.fn(...args)
}
return res;
}
// test
let obj = {
name: 'jack'
}
function test(arg1, arg2, arg3) {
console.log(this.name) // jack
console.log(arg1, arg2, arg3); // 1 2 3
}
test.myApply(obj, [1,2,3]);
实现 call()
Function.prototype.myCall = function (context, ...rest) {
context.fn = this;
var result = context.fn(...rest);
delete context.fn;
return result;
}
// test
let obj = {
name: 'jack'
}
function test(arg1, arg2, arg3) {
console.log(this.name) // jack
console.log(arg1, arg2, arg3); // 1 2 3
}
test.myCall(obj, 1,2,3);
实现 instanceof
function myInstanceOf(left, right) {
let prototype = right.prototype;
left = left.__proto__;
while(true) {
if (!left) return false;
if (left == prototype) return true;
left = left.__proto__;
}
}
console.log(myInstanceOf([], Array)); // true
实现 new
function myNew (fun, ...args) {
let obj =