Alexis
Alexis

Reputation: 25173

Find class which invoked function call in CoffeeScript

I have two classes and a global function. In the global function, I would like to to determine which class called it. Here is what the code looks like in CofffeeScript

window.pet = ()->
  alert "I was called #{by}"

class Cat
  constructor: (@name) ->
    pet()

class Dog
  constructor: (@name) ->
    pet()

Is this possible?

Upvotes: 1

Views: 378

Answers (2)

nicksweet
nicksweet

Reputation: 3999

arguments.callee.caller.name is what your looking for. The sample below should do the trick.

pet = ->
    callerName = arguments.callee.caller.name
    console.log "called by #{callerName}"

class Cat
  constructor: (@name) ->
    pet()

class Dog
  constructor: (@name) ->
    pet()

c = new Cat()
d = new Dog()

Upvotes: 0

epidemian
epidemian

Reputation: 19219

Short answer: don't.

This question is probably getting closed as a duplicate. But i'd like to point out that if you're needing to do this kind of trick to solve a problem, you're probably going to introduce another problem by using a trick like that. If the behaviour of a function needs to depend on something (like where is it being called from), make it explicit and use a parameter for that dependency; it's a pattern that everyone will easily understand.

pet = (pet) ->
  alert "I was called by #{pet.name} the #{pet.constructor.name}" 

class Cat
  constructor: (@name) ->
    pet @

new Cat 'Felix' # Output: "I was called by Felix the Cat"

That being said, Function#name is not standard, so you probably shouldn't use that either. But you can safely access a pet's "class" (i.e. its constructor function) by accessing its constructor property as shown in the example.

Upvotes: 2

Related Questions