Skip to main content

JS 手写代码

实现防抖函数

function debounce(fn,delay = 500){
let timer;
return function(){
if(timer){
clearTimeOut(timer);
}
const args = arguments;
timer = setTimeout(() => {
fn.apply(this, args) // 改变this指向为调用debounce所指的对象
}, delay)
}
}

实现节流函数

function throttle(fn, delay = 200) {
let flag = true
return function () {
if (!flag) return
flag = false
const args = arguments
setTimeout(() => {
fn.apply(this, args)
flag = true
}, delay)
}
}

实现 new

function myNew (fun, ...args) {
let obj = {};
obj.__proto__ = fun.prototype;
let res = fun.apply(obj, args);
return res instanceof Object ? res : obj;
}

function Animal(name) {
this.name = name;
}
let animal = myNew(Animal, 'dog');
console.log(animal.name) // dog

实现 bind()

Function.prototype.bindNew = function (context, ...args) {
return (...newArgs) => this.apply(context, [...args, ...newArgs]);
};

// test
const test = {
name: "fy",
showName: function (last: string) {
console.log(this.name + " is " + last);
},
};
test.showName("handsome"); // fy is handsome
test.showName.bind({
name: "Mr.fy"
})("handsome");
test.showName.bindNew({
name: "Mr.fy"
})("handsome");

实现 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);