Function.prototype.myCall = function(context) {
if (Object.prototype.toString.call(this).slice(8, -1) !== 'Function') {
console.error('只有函数有Call方法');
return;
}
context = context ? Object.create(context) : window;
const args = Array.from(arguments).slice(1);
context.fn = this;
const result = context.fn(...args);
delete context.fn;
return result;
}
Function.prototype.myApply = function(context) {
if (Object.prototype.toString.call(this).slice(8, -1) !== 'Function') {
console.error('只有函数有Call方法');
return;
}
context = context ? Object.create(context) : window;
const args = arguments[1];
context.fn = this;
const result = context.fn(...args);
delete context.fn;
return result;
}
Function.prototype.myBind = function(context) {
if (Object.prototype.toString.call(this).slice(8, -1) !== 'Function') {
console.error('只有函数有Call方法');
return;
}
context = context ? Object.create(context) : window;
const args = Array.from(arguments).slice(1);
const self = this;
const returnFn = function() {
const extArgs = Array.from(arguments);
self.apply(this instanceof returnFn ? returnFn : this, [...args, ...extArgs]);
}
const fn = function() {};
fn.prototype = this.prototype;
returnFn.prototype = new fn();
return returnFn
}
function _new(fn, ...args) {
const obj = Object.create(fn.prototype);
const ret = fn.apply(obj, args);
return obj instanceof Object ? ret : obj;
}
function debounce(fn, delay) {
let timer;
return function(...args) {
if (timer) {
clearTimeout(timer);
}
setTimeout(() => {
fn.apply()
}, delay)
}
}
function throttle(fn, wait) {
let canRun = true;
return function(...args) {
if (!canRun) {
return;
}
canRun = false;
setTimeout(() => {
fn.apply(this, ...args);
canRun = true;
},wait)
}
}
function cloneDeep(target, cache = new WeakMap()) {
if (target === null || typeof target !== 'object') {
return target;
}
if (target instanceof Date) {
return new Date(target);
}
if (target instanceof RegExp) {
return new RegExp(target);
}
if (cache.has(target)) {
return cache.get(target);
}
const obj = new target.contructor();
cache.set(target, obj);
Object.keys(key => {
obj[key] = cloneDeep(target[key], cache);
});
return obj;
}
function sayHello(param1, param2, param3) {
console.log(this.name, param1, param2);
}
const thisObj = {
name: 'zaoren'
}
sayHello.myCall(thisObj, 'day', 'day up');
sayHello.myApply(thisObj, ['day', 'day up']);
const wSayHello = sayHello.myBind(thisObj, 'day')('day up');
function Student(age) {
this.name = 'zaoren';
this.age = age;
return this;
}
const student = _new(Student, '18');
console.log('student', student);
const obj = { name: 'Jack', address: { x: 100, y: 200 } }
obj.a = obj
const newObj = cloneDeep(obj)
console.log(newObj.address === obj.address)
console