Search code examples
javascriptcoffeescriptstatechart

How to know what function a function is inside?


I am trying to create a statechart framework as a sparetime project.

CoffeeScript

Statechart.state "A", ->
  @state "B1", ->
    @state "C"
  @state "B2", ->

JavaScript

Statechart.state("A", function() {
  this.state("B1", function() {
    this.state("C");
  });
  this.state("B2", function() {
  });
});

I wonder if there is a way for the inner functions to be aware of the outer one, so that B1 and B2 know they are children of A and C knows it is a child of B1.

UPDATE: I used bind(). It worked great!


Solution

  • Use the fat arrow =>. It uses an implementation of Function.prototype.bind:

    Statechart.state "A", ->
       @state "B1", =>
           @state "C"
       @state "B2", =>
    

    In this code, @/this will always refer to the Statechart object.