new关键字实现
function _new(fn, ...arg) {
const obj = Object.create(fn.prototype)
const ret = fn.apply(obj, arg)
return ret instanceof Object ? ret : obj
}
call函数实现
function _call(obj, ...params) {
if (obj === undefined || null) obj = window
const sy = Symbol()
obj[sy] = this
const res = obj[sy](...params)
delete obj[sy]
return res
}
Function.prototype._call = _call
apply函数实现
function _apply(obj, params) {
if (Array.isArray(params) === false) throw new Error('params is not array')
if (obj === undefined || null) obj = window
const sy = Symbol()
obj[sy] = this
const res = obj[sy](...params)
delete obj[sy]
return res
}
Function.prototype._apply = _apply
bind函数实现
function _bind(obj, ...params) {
const that = this
const fn = function() {
that.call(obj, ...params)
}
return fn
}
Function.prototype._bind = _bind