Implementing the apply Function Manually
Steps to implement the apply function:
Determine if the calling object is a function. Even though it’s defined on the function’s prototype, there may be instances where it is invoked using methods like call.
Check if the incoming context object exists; if not, set it to window.
Assign the function as a property of the context object.
Determine if the parameter values have been passed in.
Invoke the method using the context object and save the returned result.
Remove the property that was just added.
Return the result
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21// apply
Function.prototype.myApply = function(context) {
if (typeof this !== "function") {
throw new TypeError("Error");
}
let result = null;
// check context or set to window
context = context || window;
// set funcion
context.fn = this;
// call the method
if (arguments[1]) {
result = context.fn(...arguments[1]);
} else {
result = context.fn();
}
// del property
delete context.fn;
return result;
};
Implementing the bind Function Manually
Steps to implement the bind function:
Determine if the calling object is a function. Even though it’s defined on the function’s prototype, there may be instances where it is invoked using methods like call.
Save a reference to the current function and retrieve the rest of the passed-in parameter values.
Return a new function.
Internally, the function uses apply to bind the function call. It’s important to account for the function being used as a constructor. In such cases, the current function’s ‘this’ needs to be passed to apply, while in all other cases, the specified context object is passed.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16// bind
Function.prototype.myBind = function(context) {
if (typeof this !== "function") {
throw new TypeError("Error");
}
// get parm
var args = [...arguments].slice(1),
fn = this;
return function Fn() {
return fn.apply(
this instanceof Fn ? this : context,
args.concat(...arguments)
);
};
};