Add some methods when inherit classes #2309

Closed
searchinnerpeace opened this Issue May 8, 2012 · 2 comments

Comments

Projects
None yet
2 participants

Hi. First, I want to thanks the creator of CoffeeScript. My journey in node.js is so much easier because of you.

I'm trying to do something like this:

class Foo
  method_foo: ->
    "Foo"

class Bar extends Foo
  method_bar: ->
    "Bar"

class Get_Bar_Methods
  bar = new Bar()
  for method_name, method_itself of bar
    Get_Bar_Methods::[method_name] = method_itself

So, Get_Bar_Methods will have Bar and Foo methods, but if I only want Bar methods? Maybe CoffeeScript could have some "default methods" when classes are inherited, such Foo.class_name(), Foo.methods_names() and Foo.methods_inherited(), so I could use this:

class Get_Bar_Methods
  bar = new Bar()
  for method_name, method_itself of bar.methods_names()
    Get_Bar_Methods::[method_name] = method_itself

Instead use a dirty code, like this:

class Get_Bar_Methods

  foo = new Foo()
bar = new Bar()

  foo_methods = []

  for foo_method of foo
    foo_methods.push foo_method

  for bar_method, method_itself of bar
    if !(bar_method in foo_methods)
      Get_Bar_Methods::[bar_method] = method_itself

Method "constructor" could be used to get class name and method names of subclass:

bar = new Bar()
console.log bar.constructor.toString()
# returns:

function Bar() {
      return Bar.**super**.constructor.apply(this, arguments);
}

But function method_bar only shows itself to constructor if I use fat arrows:

class Bar extends Foo
  method_bar: =>
    "Bar"
# returns:

function Bar() {
  this.method_bar = **bind(this.method_bar, this);
  return Bar.__super**.constructor.apply(this, arguments);
}

Just an idea... thanks

Collaborator

michaelficarra commented May 8, 2012

I think you're looking to analyse the prototype.

$ coffee
------> class Foo
......>   method_foo: ->
......>     "Foo"
[Function: Foo]
------> class Bar extends Foo
......>   method_bar: ->
......>     "Bar"
[Function: Bar]
coffee> Object.getOwnPropertyNames Bar.prototype
[ 'method_bar', 'constructor' ]
coffee> 

and if you want just the "methods"

coffee> prop for prop in Object.getOwnPropertyNames(Bar.prototype) when typeof Bar::[prop] is "function"
[ 'method_bar', 'constructor' ]
coffee> 

and more generically

coffee> Function::method_names = -> prop for prop in Object.getOwnPropertyNames(@prototype) when typeof @::[prop] is "function"
[Function]
coffee> Bar.method_names()
[ 'method_bar', 'constructor' ]
coffee> 

Thanks man

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment