Search code examples
javascriptobjectcoffeescriptobject-literal

Store function reference in javascript object


I'm guessing this should be simple, but I'm stuck. How can I store a reference to a method in another prototype object (in this case actions)? In the manner below I get undefined for my someFn and anotherFn methods.

class MyClass

  constructor: ->
    console.log @actions # returns
    # returns:
    # Object {someFn: undefined, anotherFn: undefined, someText "I am some text"}

  actions:
     someFn: @someFn
     anotherFn: @anotherFn
     someText: 'I am some text'

  someFn: ->
    console.log 'I am some function'

  anotherFn: ->
    console.log 'I am another function'

I'm using CoffeeScript, but for any plain JSers our there -

  MyClass = function MyClass() {
    console.log(this.actions);
  }

  MyClass.prototype.actions = {
    someFn: MyClass.someFn,
    anotherFn: MyClass.anotherFn,
    someText: 'I am some text'
  };

  MyClass.prototype.someFn = function() {
    return console.log('I am some function');
  };

  MyClass.prototype.anotherFn = function() {
    return console.log('I am another function');
  };

Solution

  • You cannot have objects on the prototype like that. You'll want to make that an instance property:

    class MyClass
      constructor: ->
        @actions =
          someFn: @someFn
          anotherFn: @anotherFn
          someText: 'I am some text'
        console.log @actions # works as expected
    
      someFn: ->
        console.log 'I am some function'
    
      anotherFn: ->
        console.log 'I am another function'
    

    If for some reason you really needed an object with the prototype functions on it, use :: to access them (in the static context of creating the action object):

    …
      someFn: …
      anotherFn: …
      actions:
         someFn: @::someFn
         anotherFn: @::anotherFn
         someText: 'I am some text'