手写bind完整版
function fn(a, b, c, d) {
console.log(a, b, c, d);
console.log(this)
return {a:124}
}
Function.prototype.mybind = function (ctx) {
var args = Array.prototype.slice.call(arguments, 1);
var fn = this;
return function A() {
var restArgs = Array.prototype.slice.call(arguments);
var allArgs = args.concat(restArgs);
if (Object.getPrototypeOf(this) === A.prototype) {
var obj = Object.create(fn.prototype);
var result = fn.apply(obj, allArgs)
return (typeof result === 'object' && result != null) ? result : obj;
} else {
return fn.apply(ctx, allArgs);
}
}
}
const newFn = fn.mybind('ctx', 1, 2);
let result = newFn(3, 4);
console.log(result)
let result1 = new newFn(3, 4);
console.log(result1)