Function.prototype.myApply = function (context, args) {
context = context || window;
context.fn = this;
var result = context.fn(...args);
delete context.fn;
return result;
}
Function.prototype.myBind = function (context) {
var self = this;
return function () {
if (this instanceof self) {
self.apply(this, arguments);
} else {
self.apply(context, arguments);
}
}
}
Function.prototype.myCall = function (context, ...args) {
context = context || window;
context.fn = this;
var result = context.fn(...args);
delete context.fn;
return result;
}
function sum(a, b, c) { return a + b + c; }
var result = sum.myApply(null, [1, 2, 3]);
console.log(result);
var obj = { name: 'Tom' };
function sayName() { console.log(this.name); }
var sayTomName = sayName.myBind(obj); sayTomName();
function sayHello() { console.log(Hello, ${ this.name }!); }
var person = { name: 'Tom' }; sayHello.myCall(person);