一 实现apply
Function.prototype._apply = function (context) {
if (typeof this !== 'function') {
throw new TypeError('not funciton')
}
context.fn = this; //this 指向调用_apply的函数
let args = arguments[1];
let result = context.fn(...args);
delete context.fn;
return result;
}
二 实现call
Function.prototype._call = function(context,...args) {
if (typeof this !== 'function') {
throw new TypeError('not funciton')
}
context.fn = this;//同样this指向调用_call的函数。
let result = context.fn(...args);
delete context.fn;
return reusult
}
三 实现bind函数
Function.prototype._bind = function(context) {
let fn = this;
let args = [].slice.call(arguments,1);
let F =function() {
fn.apply(this instanceof F ?this:context,args.concat([...arguments]))
}//如果通过new 绑定的函数,则把fn指向新对象,否则,指向传入的context
F.prototype = fn.prototype;
//如果new一个F对象,修改new后的对象指向新fn
return F;
}
四 实现防抖函数
function debounce(fn,wait) {
let timer = null;
return function() {
clearTimeout(timer);
let args = arguments;
let context = this;
timer = setTimeout(() => {
fn.apply(context,args)
}, wait)
}
}
五 实现节流函数
function throttle(fn, wait) {
let timer = null;
return function () {
let args = arguments;
let context = this;
if (!timer) {
timer = setTimeout(() => {
fn.apply(this, args);
timer = null;
}, wait)
}
}
}
function throttle2(fn,wait) {
let prev = Date.now();
return function() {
let now = Date.now();
let context = this;
let args = arguments;
if(now-prev>=wait) {
fn.apply(context,args);
prev = Date.now()
}
}
}