-2

I am looking to dynamically create methods in JavaScript... In ruby (see below) we have define_method, do we have something similar in JavaScript?

  define_method 'name_of_the_method' do
    'method code goes in this block'
  end
Pippo
  • 905
  • 11
  • 22
  • See answer here http://stackoverflow.com/questions/3733580/javascript-variable-in-function-name-possible – Matt The Ninja Nov 16 '15 at 16:41
  • What is it that you want to do? Like, in JavaScript terms, what are you trying and what exactly do you want the code to do, and why? – Pointy Nov 16 '15 at 16:41
  • To put it another way, what is it about JavaScript function declarations or function expressions that is inadequate for your needs? – Pointy Nov 16 '15 at 16:43
  • I am looking to build a framework around protractor, and want to build a way to handle page objects efficiently... I don't want to have variables that define a path to an element, and individual functions for each element that actually map them... If I can have a function that takes element name + element path I can then use this same function to map my elements and they give me back a function for a given element – Pippo Nov 16 '15 at 16:46
  • how is this a down vote? it's a legit question of someone that never used JS... – Pippo Nov 16 '15 at 16:47
  • how can dynamically create functions in javascript, by giving an example of a different language is too broad for SO? if you are not capable of giving a useful answer to that please keep your comments to yourself... meanwhile I will use the tip @ssube provided... – Pippo Nov 16 '15 at 16:55

1 Answers1

2

Since Javascript treats functions as first-class objects, you can create and assign them at any time. Combined with the Function constructor, the equivalent would be:

function define_method (target, name, code) {
  target[name] = new Function(code);
}

This is not super friendly when it comes to taking parameters (it does not have any named params), but will dynamically create a method on the object.

If you want to attach a method to every instance of that type of object, you should use:

target.prototype[name] = new Function(code);

If you have the function ahead of time (no need to dynamically compile it), you can just assign with a dynamic name and existing function:

function define_method(target, name, fn) {
  target[name] = fn;
}

Because Javascript treats functions as objects, you can assign them to objects (class prototype or instance) at any time.

ssube
  • 47,010
  • 7
  • 103
  • 140