new操作符做了什么
- 创建一个新对象
- 将构造函数的作用域赋值给新对象
- 执行构造函数的代码(为新对象添加属性)
- 返回新对象
js实现
new操作符
function create(fn,...args) {
let obj = {};
Object.setPrototypeOf(obj,fn.prototype);
let result = fn.apply(obj,args);
return result instanceof Object? result : obj;
}
function Con(name,age) {
this.age = age;
this.name = name;
}
Con.prototype.say = function() {
console.log(this.name,this.age)
}
let obj = create(Con,'wang',22);
console.log(obj) // {age: 22, name: "wang"}
bind 实现
function bind(fn,context) {
return function() {
fn.apply(context,[...arguments].slice())
}
}
let obj = {
say:function(age) {
console.log(this.name,age)
}
}
bind(obj.say,{name:'wang'})(22); // wang 22
防抖与节流
防抖与节流的作用都是防止函数频繁调用。区别是每次触函数的间隔小于阈值,防抖只执行一次,节流会每隔一段时间调用一次。
防抖实现
function debounce(fn, wait = 1000, immedite = true) {
let timer,context,params;
let run = () => {
timer = setTimeout(() => {
timer = null;
if(!immedite) {
fn.apply(context,params);
context = params = null;
}
}, wait)
};
return function(...args) {
if (!timer) {
run();
if(immedite) {
fn.apply(this,args);
} else {
context = this;
params = args;
}
} else {
clearTimeout(timer);
run();
}
}
}
节流实现
function throttle(fn,wait = 1000) {
let timer,params,context;
let run = () => {
timer = setTimeout(()=> {
fn.apply(context,params)
timer = null;
},wait)
}
return function(...args) {
if(!timer) {
run();
params = args;
context = this;
}
}
}
Event Bus
function Event() {
this.events = new Map();
}
Event.prototype.addEvent = function (event, fn, isOnce = false) {
let events = this.events.get(event) ? this.events.get(event) : this.events.set(event, new Map()).get(event);
if (!isOnce) {
events.set(fn, fn);
} else {
events.set(fn, (...args) => {
fn.apply(this, args);
this.off(event, fn);
});
}
this.events.set(event, events);
};
Event.prototype.emit = function (event, ...args) {
let evnets = this.events.get(event);
for (let fn of evnets.values()) {
fn.apply(this, args);
}
};
Event.prototype.off = function (event, fn) {
this.events.get(event).delete(fn);
};
Event.prototype.once = function (event, fn) {};
let event = new Event();
event.addEvent("click", function (args) {
console.log(args);
});
event.addEvent(
"click",
function () {
console.log("are you ok!");
},
true
);
event.emit("click", { name: "wang hai" });
event.emit("click", { name: "liu hai" });
// 控制台
// { name: "wang hai" }
// are you ok!
// { name: "liu hai" }