1

I've encountered a 'Cannot read property 'apply' of undefined' error when trying to define a class using CoffeeScript. As I'm new to both coffeeScript and JavaScript, I can't understand this error. Could somebody please help me.

Here is my coffeeScript code:

class Test
    constructor: (@data) ->
        @sums = @calculateSum()
        console.log @sums

    calculateSum: () =>
        sums = 0
        for i in [[email protected]] by 1
            sums += @data[i]
        return sums

window.Test = Test

Thanks.

4
  • Your code is fine, seems that the source of error is somewhere else. Commented Jan 17, 2016 at 10:59
  • Btw, please note that you are indexing @data array starting from 1, so you are missing @data[0] in the sums. Commented Jan 17, 2016 at 11:02
  • @sums = eval(@data.join('+')) would do very same as your @sums = @calculateSum() method. Btw, watch out for eval as this is risky to use it, but sometimes it gets quite handy. Commented Jan 18, 2016 at 1:38
  • Explanation of the eval(@data.join('+')): this code would join all elentents of the array into a string while putting a '+' between them. Then we evaluate that string (run it as it would be a line in a JS file) to get result. Commented Jan 18, 2016 at 1:46

1 Answer 1

2

What you are exporting is the function or in object oriented terms the class

To create an actual instance of the class you new too call it with the new operator.

new Test [100,100] and running this code does the right thing for me

Also though you might want to count from 0 and up and not from 1 and up unless you are purposely skipping the first element in the array.

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

1 Comment

I was wrong in my html code, add 'new' before 'Test' works, thanks for your reply and explanation.

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.