0

Is it possible to do something like that?

Foo.add_function = function (callback_name, callback_function) {
    this.prototype[callback_name] = callback_function;
}

I need to add a function to prototype in array notation. Thank you.

5
  • @thom So you want to be able to do this: Foo.add_function('blah', function() { ... }); instead of this: Foo.prototype['blah'] = function() { ... };? Commented May 2, 2011 at 17:36
  • Yes, but this.prototype returns undefined Commented May 2, 2011 at 17:37
  • Why does this must be a function? Thank you SLaks. Commented May 2, 2011 at 17:42
  • @thom Because adding methods to Foo.prototype only makes sense if you're going to use those methods later. You create instances of Foo like so: var foo1 = new Foo(); and then call the prototype methods on those instances: foo1.blah(). If Foo is not a function, you cannot make instances of it, so having a prototype object is pointless. Commented May 2, 2011 at 17:45
  • @thom: prototype is a property of a function. Things that aren't functions do not have a prototype property. Commented May 2, 2011 at 17:50

2 Answers 2

1

Yes.
A prototype is a normal object; that will work fine.

Note that this will only work if this is a function; otherwise, prototype won't exist.

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

Comments

0

Apparently, yes:

http://jsfiddle.net/QUFXU/6/

jsfiddle is great, you should check it out when you want to test out simple stuff like this.

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.