polyfill Function.prototype.bind 函数
注意:构造函数和原型链
/**
* polyfill bind function
*/
const slice = Array.prototype.slice
const toString = Object.prototype.toString
Function.prototype.bind = Function.prototype.bind || function () {
const fn = this
if (typeof target !== 'function' || toString.call(target) !== '[object Function]') {
throw new TypeError('type error')
}
const bindThisArg = arguments[0]
const extraArgs = slice.call(arguments, 1)
function newFun() {
const args = extraArgs.concat(slice.call(arguments))
if (this instanceof newFun) {
const ret = fn.apply(this, args)
if (Object(ret) === ret) {
return ret
}
return this
}
return fn.apply(bindThisArg, args)
}
if (fn.prototype) {
const F = function() {}
F.prototype = fn.prototype
newFun.prototype = new F()
newFun.prototype.constructor = fn
}
return newFun
}
polyfill Function.prototype.bind 函数
注意:构造函数和原型链