new的实现原理
new的特点:
new一个构造函数,会自动return一个实例对象
new完成的实例化对象,_ proto _自动指向构造函数的prototype
new构造函数传参自动赋值给当前实例化对象
function objectFactory() {
// 创建一个新的对象
const obj = {}
// 获取第一个参数,arguments是类数组,不可直接调用shift方法
//此外因为 shift 会修改原数组,所以 arguments 会被去除第一个参数
const Constructor = [].shift.call(arguments)
// 将obj的原型指向构造函数的原型对象,这样obj就可以访问构造函数原型上的属性
obj.proto = Constructor.prototype
// 将构造函数的this指向obj,这样obj就可以访问到构造函数中的属性
Constructor.apply(obj, arguments);
// 返回 obj
return obj;
}
防抖和节流
防抖:在固定的时间内没有触发事件,会在固定时间结束后触发,如果固定时间内触发事件了,会在延长固定时间内触发
节流:无论在固定时间内是否有事件触发,都会按照固定时间规律触发
防抖代码
// 防抖
function debounce(fn, wait) {
var timeout = null;
return function() {
if(timeout !== null) clearTimeout(timeout);
timeout = setTimeout(fn, wait);
}
}
// 处理函数
function handle() {
console.log(Math.random());
}
// 滚动事件
window.addEventListener(‘scroll’, debounce(handle, 1000));
节流代码
// 节流throttle代码(定时器):
var throttle = function(func, delay) {
var timer = null;
return function() {
var context = this;
var args = arguments;
if (!timer) {
timer = setTimeout(function() {
func.apply(context, args);
timer = null;
}, delay);
}
}
}
function handle() {
console.log(Math.random());
}
window.addEventListener(‘scroll’, throttle(handle, 1000));