要开始写了
Function.prototype._bind = function (context, ...args) {
const _this = this
const newThis = context
return function () {
return _this._apply(newThis, args)
}
}
Function.prototype._apply = function (context, args) {
if (typeof this !== 'function') {
return new TypeError('非函数')
}
context = context || window
const fnSymbol = Symbol()
context[fnSymbol] = this
const result = args ? context[fnSymbol](...args) : context[fnSymbol]()
delete context[fnSymbol]
return result
}
下面来执行一下
function Hello(name) {
console.log(`Hello, ${name}! My name is ${this.name}`);
}
const person = { name: 'zhangsan' };
const boundHello = Hello._bind(person, 'laoli');
boundHello();
function add(a, b) {
return a + b;
}
add._apply(null, [1, 2])
写完了就是这么朴实无华。