防抖函数
function debounce ( fn, delay, immediate) {
let timer = null ;
return function ( ) {
const _this = this ;
const args = [ ... argumets] ;
if ( immediate && ! timer) {
fn. apply ( _this, args) ;
}
timer && clearTimeout ( timer) ;
timer = setTimeout ( _ => fn. apply ( _this, args) , delay) ;
}
}
截流函数
function thtottle ( fn, delay) {
let start = Date. now ( ) ;
let timer = null ;
return funciton ( ) {
const _this = this ;
const args = [ ... argumets] ;
let current = Date. now ( ) ;
let remain = delay - ( current - start) ;
timer && clearTimeout ( timer) ;
if ( remain <= 0 ) {
fn. apply ( _this, args) ;
start = Date. now ( ) ;
} else {
setTimeout ( _ => fn. apply ( _this, args) , remain)
}
}
}
对象深拷贝
function deepClone ( obj) {
let result;
if ( Array. isArray ( obj) ) {
result = [ ] ;
} else if ( obj && typeof obj === 'object' ) {
result = {
} ;
} else {
return obj;
}
for ( let key in obj) {
if ( obj. hasOwnProperty ( key) ) {
result[ key] = deepClone ( obj[ key] )
}
}
return result;
}
模拟promise
class MockPromise {
constructor ( fn) {
this . state = pending;
this . value = undefined;
this . reason = undefined;
const resolve = value => {
if ( this . state === 'pending' ) {
this . state = 'fulfilled' ;
this . value = value;
}
} ;
const reject = value => {
if ( this . state === 'pending' ) {
this . state = 'rejected'
this . reason = value
}
} ;
try {
fn ( resolve, reject) ;
} catch ( e ) {
reject ( e) ;
}
}
then ( onResolve, onReject) {
switch ( this . state) {
case 'fulfilled' :
onFulfilled ( ) ;
break ;
case 'rejected' :
onRejected ( ) ;
break ;
default :
}
}
}
模拟create
function mockCreate ( obj) {
Function F ( ) {
} ;
F . prototype = obj;
return new F ( ) ;
}
模拟call实现
if ( ! Function. prototype. call) {
Function. prototype. call = function ( context) {
if ( typeof this !== 'function' ) {
}
context = context || window;
const args = arguments. slice ( 1 ) ;
context. fn = this ;
const result = context. fn ( ... args) ;
delete context. fn;
return result;
}
}
模拟apply实现
if ( ! Function. prototype. apply) {
Function. prototype. apply = function ( context) {
if ( typeof this !== 'function' ) {
}
context = context || window;
context. fn = this ;
const args = arguments. slice ( 1 ) ;
const result = context. fn ( ... args) ;
delete context. fn;
return result;
}
}
模拟bind实现
if ( ! Function. prototype. bind) {
Function. prototype. bind = function ( context) {
if ( typeof this !== 'function' ) {
}
var _this = this ,
fNOP = function ( ) {
} ,
args = Array. prototype. slice. call ( arguments, 1 ) ,
fBound = function ( ) {
_this. call ( context, args. concat ( Array