JS Coding Questions Logo
JS Coding Questions
#444💼 Interview💻 Code

How do you create your own bind method using either call or apply method?

Advertisement

728x90

The custom bind function needs to be created on Function prototype inorder to use it as other builtin functions. This custom function should return a function similar to original bind method and the implementation of inner function needs to use apply method call.

The function which is going to bind using custom myOwnBind method act as the attached function(boundTargetFunction) and argument as the object for apply method call.

js
1Function.prototype.myOwnBind = function (whoIsCallingMe) {
2
3if (typeof this !== "function") {
4  throw new Error(this + "cannot be bound as it's not callable");
5}
6
7const boundTargetFunction = this;
8
9return function () {
10  boundTargetFunction.apply(whoIsCallingMe, arguments);
11};
12};

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 15

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
444of476
How do you create your own bind method using either call or apply method? | JSCodingQuestions.com