Function.prototype.myBind = function(context = window, ...args) {
let self = this;
let fBound = function(...innerArgs) {
return self.apply(
this instanceof fBound ? this : context,
args.concat(innerArgs)
);
}
fBound.prototype = Object.create(this.prototype);
return fBound;
}
function Person(name, age) {
console.log('Person name:', name);
console.log('Person age:', age);
console.log('Person this:', this);
}
Person.prototype.say = function() {
console.log('person say');
}
function normalFun(name, age) {
console.log('普通函数 name:', name);
console.log('普通函数 age:', age);
console.log('普通函数 this:', this);
}
var obj = {
name: 'poetries',
age: 18
}
var bindFun = Person.myBind(obj, 'poetry1')
var a = new bindFun(10)
a.say()
var bindNormalFun = normalFun.myBind(obj, 'poetry2')
bindNormalFun(12)
console