Function.prototype.myBind = function (context, ...args) { if (typeof (this) !== 'function') { thrownewTypeError('The bound object needs to be a function'); } const _this = this;
returnfunctionnewFunction() { // 使用了 new if (thisinstanceof newFunction) { returnnew _this(...args); } else { return _this.call(context, ...args); } } }
let a = { name: 'poetries', age: 12 } functionfoo(a, b) { console.log(this.name); console.log(this.age); console.log(a); console.log(b); } foo.myBind(a, 1, 2)(); // => 'poetries'