var name = 'global name'
const club = {
name: 'Hello World',
getName: function(a, b, c) {
console.log(this.name, a, b, c);
},
getName2: () => {
console.log(this.name);
}
}
// club.getName(1, 2, 3);
// club.getName2();
Function.prototype.myCall = function() {
const context = arguments[0];
const argsArray = [];
for (let i = 1; i < arguments.length; i++) {
argsArray.push(arguments[i]);
}
const fn = this;
context.fn = fn;
// es6
context.fn(...argsArray);
// es5 使用 eval
// eval("context.fn(" + argsArray + ")");
delete context.fn;
}
Function.prototype.myApply = function() {
const context = arguments[0];
const argsArray = arguments[1];
const fn = this;
context.fn = fn;
// es6
context.fn(...argsArray);
// es5 使用 eval
// eval("context.fn(" + argsArray + ")");
delete context.fn;
}
Function.prototype.myBind = function() {
const context = [].shift.call(arguments);
const fn = this;
const argsArray = arguments;
return function() {
// es6
fn.call(context, ...argsArray, ...arguments);
// es5
// eval("fn.call(context, " + [].slice.call(argsArray) + "," + [].slice.call(arguments) + ")");
};
}
const test = { name: 'test' }
// club.getName.myCall(test, 1, 2, 3);
// club.getName.myApply(test, [4, 5, 6]);
const getNameBinded = club.getName.myBind(test, 1, 2);
getNameBinded(3);
console