手写new函数
function _new() {
const obj = new Object();
const [constructor, args] = [...arguments];
obj.__proto__ = constructor.prototype;
const ret = constructor.apply(obj, args);
return typeof ret === 'object' ? ret : obj;
}
手写bind函数
Function.prototype.mybind = function(context) {
if(typeof this !== 'function'){
throw new TypeError('类型错误');
}
const fn = this;
const args = [...arguments].slice(1);
return function Fn() {
const that = this instanceof Fn ? new Fn(...arguments) : context;
fn.apply(that, args.concat(...arguments));
}
}
手写call 函数
Function.prototype.mycall = function(context) {
if(typeof this !== 'function') {
throw new TypeError('类型错误');
}
context = context || window;
context.fn = this;
const args = [...arguments].slice(1);
const result = context.fn(...args);
delete context.fn;
return result;
}
手写 apply 函数
Function.prototype.myapply = function(context) {
if(typeof this !== 'function') {
throw new TypeError('类型错误')
}
context = context || window
context.fn = this
const result
if(arguments[1]){
result = context.fn(...arguments[1])
}else {
result = context.fn()
}
delete context.fn
return result
}