最近在面試,面試官動不動就讓寫一個原生方法的實現,那咱們就在這裏寫一下常見的一些實現:
1.bind
Function.prototype.bind2 = function (context) {
var self = this;
return function () {
self.apply(context);
}
}
2.promise
class Promise {
result: any;
callbacks = [];
failbacks = [];
constructor(fn) {
fn(this.resolve.bind(this), this.reject.bind(this));
}
resolve(res) {
if (this.callbacks.length > 0) this.callbacks.shift()(res, this.resolve.bind(this), this.reject.bind(this));
}
reject(res) {
this.callbacks = [];
if (this.failbacks.length > 0) this.failbacks.shift()(res, this.resolve.bind(this), this.reject.bind(this));
}
catch(fn) {
this.failbacks.push(fn);
}
then(fn) {
this.callbacks.push(fn);
return this;
}
}
3.new的實現
function create() {
// 創建一個空的對象
let obj = new Object()
// 獲得構造函數
let Con = [].shift.call(arguments)
// 鏈接到原型
obj.__proto__ = Con.prototype
// 綁定 this,執行構造函數
let result = Con.apply(obj, arguments)
// 確保 new 出來的是個對象
return typeof result === 'object' ? result : obj
}
4.函數防抖
// func是用戶傳入需要防抖的函數
// wait是等待時間
const debounce = (func, wait = 50) => {
// 緩存一個定時器id
let timer = 0
// 這裏返回的函數是每次用戶實際調用的防抖函數
// 如果已經設定過定時器了就清空上一次的定時器
// 開始一個新的定時器,延遲執行用戶傳入的方法
return function(...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}
5.函數節流
function throttle(method,delay){
var timer=null;
return function(){
var context=this, args=arguments;
clearTimeout(timer);
timer=setTimeout(function(){
method.apply(context,args);
},delay);
}
}
6.深拷貝
function deepClone(obj) {
let result = typeof obj.splice === "function" ? [] : {};
if (obj && typeof obj === 'object') {
for (let key in obj) {
if (obj[key] && typeof obj[key] === 'object') {
result[key] = deepClone(obj[key]);//如果對象的屬性值爲object的時候,遞歸調用deepClone,即在吧某個值對象複製一份到新的對象的對應值中。
} else {
result[key] = obj[key];//如果對象的屬性值不爲object的時候,直接複製參數對象的每一個鍵值到新的對象對應的鍵值對中。
}
}
return result;
}
return obj;
}
7.extends實現
//子類 extends 父類
Function.prototype.extends = function(func, options){
for(var key in func.prototype){
this.prototype[key] = func.prototype[key];
}
for(var name in options){
this.prototype[name] = options[name];
}
}
總結:以上是面試過程中常見的方法實現,只是簡單的實現,面試的各位可以看下準備下。