function myCreate(obj) {
function f() {}
f.prototype = obj;
return new f();
}
function myInstanceof(obj, f) {
let proto = Object.getPrototypeOf(obj);
let prototype = f.prototype;
while (proto) {
if (proto == prototype) return true;
proto = Object.getPrototypeOf(proto);
}
return false;
}
function myNew() {
let obj = null;
let constructor = Array.prototype.shift.apply(arguments);
if (typeof constructor !== 'function') {
throw Error('参数类型错误');
return;
}
obj = Object.create(constructor.prototype);
let result = constructor.apply(obj, arguments);
let flag = result && (typeof result === 'object' || typeof result === 'function');
return flag ? result : obj;
}
function debounce(fn, wait) {
let timer = null;
return function() {
let context = this;
let args = arguments;
if (timer) {
clearTimeout(timer);
timer = null
}
timer = setTimeout(() => {
fn.apply(context, args)
}, wait)
}
}
function throttle(fn, wait) {
let previous = 0
return function(...args) {
let now = +new Date();
if (now - previous > wait) {
previous = now;
fn.apply(this, args)
}
}
}
function getType(value) {
if (value === null) {
return value + ''
}
if (typeof value === 'object') {
return Object.prototype.toString.apply(value).slice(8, -1);
} else {
return typeof(value)
}
}
Function.prototype.myCall = function(context) {
if (typeof this !== 'function') {
throw Error('调用类型错误');
}
let args = [...arguments].slice(1)
context = context || window;
context.fn = this;
let result = context.fn(...args);
delete context.fn;
return result;
}
Function.prototype.myApply = function(context) {
if (typeof this !== 'function') {
throw Error('调用类型错误');
}
let args = arguments[1],
result = null;
context = context || window;
context.fn = this;
if (args) {
result = context.fn(...args);
} else {
result = context.fn();
}
delete context.fn;
return result;
}
Function.prototype.myBind = function(context) {
if (typeof this !== 'function') {
throw Error('调用类型错误');
}
context = context || window;
let fn = this;
let args = [...arguments].slice(1);
return function() {
return fn.apply(this instanceof fn ? this : context, args.concat(...arguments))
}
}
function currying(fn, ...args) {
let len = fn.length;
return function(...params) {
let _args = [...args, ...params];
if (_args.length < len) {
return currying.call(this, fn, ..._args);
} else {
return fn.apply(this, _args)
}
}
}
function shallowCopy(obj) {
let newObj = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = obj[key];
}
}
return newObj;
}
function deepCopy(obj) {
let newObj = Array.isArray(obj) ? [] : {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
newObj[key] = typeof obj[key] === 'object' ? deepCopy(obj[key]) : obj[key];
}
}
return newObj;
}
console