How to list methods of inherited classes in CoffeeScript or Javascript
Example:
class Complex
constructor: (@a, @b) ->
conjugate: -> new Complex(@a, -@b)
class ComplexSon extends Complex
开发者_Go百科 constructor: (@a, @b) ->
@c = 3.14
magnitude: -> @a*@a + @b*@b
I have defined the following method:
dumpMethods = (klass) ->
Object.getOwnPropertyNames(klass.property).sort()
Test cases:
dumpMethods(Complex) == ['conjugate', 'constructor']
# success
dumpMethods(ComplexSon) == ['conjugate', 'constructor', 'magnitude']
# fails, returns ['constructor', 'magnitude']
What is the correct definition of dumpMethods?
ban,
Javascript (and consequently coffee script) use prototypal objects.
I suggest you read about it because the matter is rather complex.
Trying to summarize, each object has a prototype. The prototype is itself an object, has its own properties, and also has a prototype, and so on.
The chain of prototypes actually defines the class hierarchy. So in you case, ComplexSon will have a prototype that is Complex, that will have a prototype that is Object itself, the root of all object hierarchies in javascript.
When you call a method on an instance, javascript will search for that method on that instance, then in its prototype, then up on the chain. The first one found is the method it will execute.
As in most programming languages, you can go "up" the hierarchy and see superclasses, but rarely you can go down cause it is rarely needed by the language interpreter itself. However there are some workarounds, like ones used by prototype, to know the subclasses of a given class, but AFAIK they are not in the lauage itself, most often they simply keeps track of defined classes.
Regarding the methods, in your code you are looking at the properties of ComplexSon, that correctly consist of only two methods. The other one (coniugate) is not there cause it is reached via the prototype, you can list them all by recursively going up the prototype chain.
Based on Gianni's answer I ended up with the following implementation. dumpMethods traverses against the root class, Object, but avoids listing the methods in Object.
dumpMethods = (klass) ->
res = []
k = klass.prototype
while k
names = Object.getOwnPropertyNames(k)
res = res.concat(names)
k = Object.getPrototypeOf(k)
break if not Object.getPrototypeOf(k) # suppress Object
res.unique().sort()
精彩评论