手写bind方法,最容易忽略的地方就是需要判断函数是否为构造函数,要不然this指向有问题
Function.prototype.MyBind = function (ctx) {
if (typeof this !== 'function') {
return 111
}
let args = [...arguments].slice(1)
let fn = this
return function Fn() {
// return是防止函数里有return方法
// 需要判断是否为构造函数
return fn.apply(this instanceof Fn ? this : ctx, args.concat(...arguments))
}
}