call

Call (obj, arg1, arg2…) Change fnA’s this point to obj, execute fnA and return the result

Function.prototype.myCall = function(context = window, ... args) { context = context || window; context.fn = this; var result = context.fn(... args); delete context.fn; return result; };Copy the code

apply

> fnA. Apply (obj, [arg1, arg2… ), modifies fnA’s this to point to obj, executes fnA and returns its execution result

Function.prototype.myApply = function(context = window, args = []) { context = context || window; context.fn = this; var result = context.fn(... args); delete context.fn; return result; };Copy the code

bind

Bind (obj, arg1, arg2…) FnA, role: modify the function of this point to obj, return to revised this point to the new function (note: similar to the call, just do not perform the bind returns new function)

Function.prototype.myBind = function(context, ... args) { var _this = this; return function() { return _this.myApply(context, args); }; };Copy the code

The test case

var obj = { a: 10, b: 20 }; function test(key1, key2) { console.log(this[key1] + this[key2]); } test.myCall(obj, "a", "b"); // 30a test.myApply(obj, ["a", "b"]); // 30 test.bind(obj, "a", "b")(); / / 30Copy the code