ES5写法
Function.prototype._bind = function () {
if (typeof this !== "function") {
throw new TypeError('Error')
}
let self = this
let args = Array.prototype.slice.call(arguments, 1) //取出除第一个参数的所有参数
let _this = arguments[0]
return function () {
return self.apply(_this, args)
}
}
function fn() {
this.a = arguments[0]
console.log('a:' + this.a);
console.log('name:' + this.name);
}
let obj = {
name: 'zs'
}
console.log(fn._bind(obj, ['apply', '0', '1'])(1, 3));
ES6写法
// ES6写法
Function.prototype._bind = function (...args) {
if (typeof this !== "function") {
throw new TypeError('Error')
}
let self = this
let context = args.shift() //shift 方法是将数组中的第一个数删除,然后然后返回删除的数
return function (...arg) {
console.log(args[0].concat([...arg]));
return self.apply(context, args[0].concat([...arg]))
}
}
function fn() {
this.a = arguments[0]
console.log('a:' + this.a);
console.log('name:' + this.name);
}
let obj = {
name: 'zs'
}
console.log(fn._bind(obj, ['apply', '0', '1'])(1, 3));