简单版,不带参数
Function.prototype.my_bind = function(targ){
var _this = this;
return function(){
_this.apply(targ)
}
}
function f() {
console.log(`${this.name}`);
}
var o = {
name: 'liu'
};
f.my_bind(o)();
带参数
Function.prototype.my_bind = function(){
var _this = this;
var targ = Array.prototype.shift.call(arguments)
var arg = Array.prototype.slice.call(arguments)
return function(){
_this.apply(targ, Array.prototype.concat.apply(arg, arguments))
}
}
function f(a,b,c) {
console.log(`${this.name} ${a} ${b} ${c}`);
}
var o = {
name: 'liu'
};
f.my_bind(o, 1, 2)(3);