0

I have following code:

class Circle
  constructor: (@center, @radius, @color) ->

  @Red: (@center, @radius) ->
    new @ center, radius, 'red'

class Point
  constructor: (@x, @y) ->

I can create red circle like this: red_circle = Circle.Red(new Point(0,0), 10)

But following code doesn't work:

obj = Circle.Red
red_circle = obj(new Point(0,0), 10)

What am I doing wrong?

2 Answers 2

2

Circle.Red(...) sets this (@) to Circle; so new @ = new Circle.

obj(...) does not set this, so new @ is invoking new on something else (depending on the context).

You can fix this by binding: obj = Circle.Red.bind(Circle)

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

Comments

1

When invoked as obj(), there's no context to the call; meaning this inside the function is not Circle, but rather likely window. You need to bind the context to preserve it:

obj = Circle.Red.bind Circle

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.