-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
6
  • See answer here stackoverflow.com/questions/3733580/… Commented Nov 16, 2015 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? Commented Nov 16, 2015 at 16:41
  • To put it another way, what is it about JavaScript function declarations or function expressions that is inadequate for your needs? Commented Nov 16, 2015 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 Commented Nov 16, 2015 at 16:46
  • how is this a down vote? it's a legit question of someone that never used JS... Commented Nov 16, 2015 at 16:47

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.