Reputation: 125
I want to use @Type
in a if statement, but it seems as if it is not recognizing @Type
. Is there a way to get @Type
so that I can use it in the superclass?
class opponent
constructor: (ID, Level, Name) ->
@ID = ID
@Level = Level
@Name = Name
@Health = if @Level is 1
@Level * 5
else if 2 <= @Level <= 4
(@Level * 6) - (@Level * 2)
@Luck = if @Type is "Snake"
Math.ceil(@Level * 1.25) + 5
else
Math.ceil(@Level * 1.25)
@attackDamage = 0
@defenseDoubled = false;
@Poisoned = false;
@Burned = false;
@Frozen = false;
@defend: ->
@Defense *= 2
@DefenseDoubled = true;
@undefend: ->
@Defense /= 2
@DefenseDoubled = false;
class Snake extends opponent
@Type: "Snake"
Upvotes: 0
Views: 213
Reputation: 12129
Your code does not work because in the parent class, you are referencing an instance variable, @Type
, but in the Snake subclass, you are defining a class variable, @Type: "Snake"
.
To declare the Type
variable as instance variable, declare it without the @
sign:
class Snake extends opponent
Type: "Snake"
To further expand on hpaulj's answer - you always want to keep your code DRY, so the logic that calculates the @Luck attribute should be only defined in the parent class. Consider the following example:
class opponent
constructor: ( args... ) ->
# ... your logic
@Luck = Math.ceil(@Level * 1.25) + ( @LuckFactor? or 0 )
class Snake extends opponent
LuckFactor: 5
Upvotes: 0
Reputation: 231395
This doesn't answer your question (of how to make a subclass attribute visible to the parent class), but it should produce the same result - in a manner that easily expands. You can add more subclasses without going back and changing opponent
each time.
class opponent
constructor: (ID, Level, Name) ->
@ID = ID
@Level = Level
@Name = Name
@Health = if @Level is 1
@Level * 5
else if 2 <= @Level <= 4
(@Level * 6) - (@Level * 2)
@Luck = Math.ceil(@Level * 1.25)
@attackDamage = 0
# ...
class Snake extends opponent
constructor : (ID, Level, Name) ->
# use parent constructor to create the object
# and then customize the values for this class
super
@Luck = Math.ceil(@Level * 1.25) + 5
Upvotes: 1
Reputation: 434665
You can get to the "class" using the constructor
property:
Returns a reference to the
Object
function that created the instance's prototype.
So if s
is a snake, then s.constructor
is Snake
. That means that you can do things like this:
class A
m: -> console.log(@constructor.type)
class B extends A
@type = 'B'
class C extends A
@type = 'C'
(new B).m()
(new C).m()
and get 'B'
and 'C'
in the console.
Demo: http://jsfiddle.net/ambiguous/bE6jh/
In your particular case, you'd want to look at @constructor.Type
inside the method that wants to know the type.
Upvotes: 1