2

I know that a CoffeeScript class can be extended like this:

Dog::bark = ->
  console.log("bark")

I want to be able to do this dynamically. For example, I want to do something like this:

sounds = [ "bark", "woof", "grrr", "ruff" ] 

for sound in sounds
  Dog::[sound] = ->
    console.log(sound)

The equivalent JavaScript would be:

var sounds = [ "bark", "woof", "grrr", "ruff" ];

for (var i = 0; i < sounds.length; i++) 
{
  var sound = sounds[i];

  Dog.prototype[sound] = function() {
    console.log(sound);
  };
}

How can I do this with CoffeeScript?

0

1 Answer 1

4

You almost have it, you just need to toss a do in there to force sound to be evaluated when you build the new method:

sounds = [ "bark", "woof", "grrr", "ruff" ] 
for sound in sounds
    do (sound) ->
        Dog::[sound] = -> console.log(sound)

If you don't include the do you'll end up with all four methods doing console.log('ruff'). Adding the do converts the for loop's body to a self-executing function. From the fine manual (bottom of the section):

When using a JavaScript loop to generate functions, it's common to insert a closure wrapper in order to ensure that loop variables are closed over, and all the generated functions don't just share the final values. CoffeeScript provides the do keyword, which immediately invokes a passed function, forwarding any arguments.

Demo: http://jsfiddle.net/ambiguous/YAqJu/

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

3 Comments

Is Dog::[sound] really the correct syntax? I was just guessing.
@LandonSchropp: Yes it is. :: is just prototype and [sound] is a normal object property reference. So Dog::[sound] is the same as Dog.prototype[sound] and that's what you want to add methods.
Nice catch on the closure wrapper as well. I wasn't even thinking about that.

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.