malcoauri
malcoauri

Reputation: 12189

Classes in CoffeeScript

There is the following class in CoffeScript:

class MyClass

  f: (@x) ->

Translating this code in JS we have:

(function() {
  var MyClass;

  MyClass = (function() {
    function MyClass() {}

    MyClass.prototype.f = function(x) {
      this.x = x;
    };

    return MyClass;
  })();
}).call(this);

I don't understand why in order to add function to MyClass I should use prototype for it; why I can't use 'MyClass.f = function(x) ... " ? Please, explain it to me. Thanks.

Upvotes: 1

Views: 79

Answers (2)

hpaulj
hpaulj

Reputation: 231355

If you define

class MyClass 
    f: (@x) ->
    @g: (@x) ->
m = new MyClass()

you'll find that, MyClass has a g attribute, but not f, while m has an f, but not g.

To access g from m, you have to use m.constructor.g.

Also MyClass.prototype == m.__proto__.

To really understand this you need to dig into the prototype inheritance structure of Javascript.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new

When the code new foo(...) is executed, the following things happen:

  • A new object is created, inheriting from foo.prototype.

  • The constructor function foo is called with the specified arguments...

  • The object returned by the constructor function becomes the result of the whole new expression. ...

So the key point is that the new object inherits (is effectively a copy of) from the class prototype.

Upvotes: 2

Kyle Needham
Kyle Needham

Reputation: 3389

You don't have to use the prototype chain, you can assign static methods as well like this:

class MyClass

  @f: (@x) ->

Which will output:

var MyClass;

MyClass = (function() {
  function MyClass() {}

  MyClass.f = function(x) {
    this.x = x;
  };

  return MyClass;

})();

Upvotes: 0

Related Questions