new
1.创建一个空对象{}
2.将构造函数的作用域赋值给新对象(this指向这个新对象)
3.执行构造函数为这个新对象添加属性
4.如构造函数有返回值则返回,没有则返回新对象
valueOf() 和 toString()
共同点:valueOf() 和 toString() 会在输出对象的时候自动调用。
不同点:二者并存的情况下,在数值运算中,优先调用了valueOf,字符串运算中,优先调用toString
Reflect、Proxy
Reflect
Reflect是对Object操作的增强,Reflect的get和set,需要操作的属性部署了getter或者setter时,则读取函数的this绑定receiver。
1.优化Object的一些操作方法及合理的返回Object的操作结果,
2.对一些命令式的Object行为函数化,
3.从Reflect对象上拿Object对象内部方法,确保Object的原生行为能够正常运行
4。Reflect和Proxy是相辅相成的。
Proxy
Proxy用于拦截某些特定操作的默认行为
深拷贝
function checkType(obj) {
return Object.prototype.toString.call(obj).slice(8,-1);
}
function deepClone(obj,hash = new WeakMap()) {
if(checkType(obj) === 'Date') {
return new Date(obj)
}
if(checkType(obj) === 'RegExp') {
// regExp.source 正则对象的源模式文本
// regEpx.flags 正则表达式对象的标志字符串
// regEpx.lastIndex 下次匹配开始的字符串索引位置
let temp = new RegExp(obj.source,obj.flags);
temp.lastIndex = obj.lastIndex;
return temp;
}
if(obj === null || typeof obj !=='object') {
return obj
}
if(hash.has(obj)){
return hash.get(obj);
}
let newObj = new obj.constructor
hash.set(obj, newObj);
Reflect.ownKeys(obj).forEach(key => {
if(typeof obj[key] === 'object' && obj[key] !== nll) {
newObj[key] = deepClone(obj[key], hash);
} else {
newObj[key] = obj[key];
Object.defineProperty(newObj, key, Object.getOwnPropertyDescriptor(obj, key));
}
})
return newObj;
}
防抖节流
function throttle(fn,time) {
let last;
return function() {
let now = Date.now();
if (!last) {
fn.apply(this,arguments);
last = now;
return;
}
if(now - last >= time) {
fn.apply(this,arguments);
last = now;
}
}
}
// m = throttle(b,1000)
// m(1)
// m(2)
// m(3)
// setTimeout(function(){m(4)},1000)
function debounce(fn,time) {
let timer
return function() {
let args = arguments;
if(timer) {
clearTimeout(timer);
timer = null
}
setTimeout(function() {
fn.apply(this,args)
timer = null;
},time)
}
}
函数柯里化
function curry(fun) {
console.log(arguments.length);
return function judgeCurry(...args) {
return fun.length > args.length ?
(...arg1) => judgeCurry(...args,...arg1):
fun(...args);
}
}