防抖
function debounce(func, wait,immediate) {
let timer = null
return function () {
let context = this
let args = arguments
const callNow=!timer
if (timer) {
clearTimeout(timer)
}
if(immediate){
timer = setTimeout(() => {
timer=null
}, wait);
if (callNow) func.apply(context, args)
}
else{
timer = setTimeout(() => {
func.apply(context, args)
}, wait);
}
}
}
节流
function throttle(func,wait){
let lastTime=0
return function(...args){
let now =new Date()
if(now-lastTime>wait){
lastTime=now
func.apply(this,...args)
}
}
}
call
Function.prototype.myCall=function(context=window,...args){
let key=Symbol('key')
console.log('this:',this)
context[key]=this
let result=context[key](...args)
delete context[key]
return result
}
function f(a, b) {
console.log(a + b)
console.log(this.name)
}
let obj = {
name: 1
}
console.log(f.myCall(obj, 1, 2) )
apply
Function.prototype.myApply=function(content=window,args){
let key=Symbol('key')
content[key]=this
let result=content[key](...args)
delete content[key]
return result
}
function f(a, b) {
console.log(a)
console.log(b)
console.log(this.name)
}
let obj = {
name: '张三'
}
console.log( f.myApply(obj, [1, 2]) )
instanceof
function myinstanceof(a,b){
let test =Object.getPrototypeOf(a)
while(true){
if(test==null) {
return false
}
if(test ===b.prototype ){
return true
}
test=Object.getPrototypeOf(test)
}
}
let a=new Object()
console.log(a)
console.log(this.myinstanceof(a,Object))
New
function myNew(fn,...args){
let instance=Object.create(fn.prototype)
let res=fn.apply(instance,args)
return typeof res==='object'?res:instance
}
function Car(make, model, year) {
this.make = make;
this.model = model;
this.year = year;
}
const car1 = myNew( Car,'Eagle', 'Talon TSi', 1993);
console.log(car1);
Objective.create()
function myCreate(test){
function F() { }
F.prototype = test;
return new F()
}
const person = {
isHuman: false,
printIntroduction: function () {
console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
}
};
const me = myCreate(person);
const ms = Object.create(person);
console.log(me)
console.log(ms)