w3resource

JavaScript: Create a function that invokes the method at a given key of an object

JavaScript fundamental (ES6 Syntax): Exercise-60 with Solution

Write a JavaScript program to create a function that invokes the method at a given key of an object. Optionally, add any parameters that are supplied to the beginning of the arguments.

  • Return a function that uses Function.prototype.apply() to bind context[fn] to context.
  • Use the spread operator (...) to prepend any additional supplied parameters to the arguments.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
const bindKey = (context, fn, ...args) =>
  function() {
    return context[fn].apply(context, args.concat(...arguments));
  };

const freddy = {
  user: 'fred',
  greet: function(greeting, punctuation) {
    return greeting + ' ' + this.user + punctuation;
  }
};
const freddyBound = bindKey(freddy, 'greet');
console.log(freddyBound('hi', '!'));

Sample Output:

hi fred!

Flowchart:

flowchart: Create a function that invokes the method at a given key of an object

Live Demo:

See the Pen javascript-basic-exercise-60-1 by w3resource (@w3resource) on CodePen.


Improve this sample solution and post your code through Disqus

Previous: Write a JavaScript program to create a function that invokes fn with a given context, optionally adding any additional supplied parameters to the beginning of the arguments.
Next: Write a JavaScript program to cast the provided value as an array if it's not one.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.