自定义bind
Function.prototype.mybind = function (context, ...args1) {
// 判断是否为函数
if (typeof this !== 'function') {
throw new Error('Error');
}
// 默认绑定对象为window
context = context || window;
// 指向函数的this
_this = this;
return function (...args2) {
return _this.apply(context, args1.concat(args2));
}
}
var name = 'window';
var hello = {
name: 'hello',
fn() {
console.log(this.name);
console.log(...arguments);
}
}
var world = {
name: "world"
}
hello.fn.mybind(world, 1, 2, 3)(4);
执行结果:
world
1 2 3 4