new的实现原理

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值