constructor - CoffeeScript Class Variable undefined 1.9 -
so looking @ coffeescript code not mine, trying understand why class variable undefined. coffeescript runtime 1.9
class commandparser obj: message: null indicator: 'warning' stacktrace: null result: null isexception: false constructor: (@command, @params, @result) -> @obj.result = result //@obj undefined i trying understand why @obj undefined
assuming indentation looks like:
class commandparser obj: message: null indicator: 'warning' stacktrace: null result: null isexception: false constructor: (@command, @params, @result) -> @obj.result = result then you're not getting typeerror @obj being undefined, you're getting referenceerror because there no result variable.
when say:
m: (@i) -> ... for method @i in argument list automatically assigns parameter value @i instance variable on object there won't i local variable. constructor:
constructor: (@command, @params, @result) -> automatically sets @command, @params, , @result instance variables when call there no result local variable anywhere in sight. if want @ result value you'd @ @result:
constructor: (@command, @params, @result) -> @obj.result = @result # ------------^ or you'd leave @ off in argument list:
constructor: (@command, @params, result) -> @obj.result = result that's obvious bug taken care of, hidden bug comes next. when define @ class level:
class c p: { a: 11 } then p part of c's prototype shared instances of c. in case, there 1 @obj object shared instances of commandparser if say:
c1 = new commandparser('c1', 'p1', 'r1') c2 = new commandparser('c2', 'p2', 'r2') then both c1.obj.result , c2.obj.result 'r2' because they're both using same @obj reference.
defining mutable values @ class level mistake, define them in constructor each instance gets own:
class commandparser constructor: (@command, @params, @result) -> @obj = message: null indicator: 'warning' stacktrace: null result: @result isexception: false if want define them @ class level documentation purposes you'd want clone in constructor:
class commandparser obj: message: null indicator: 'warning' stacktrace: null result: null isexception: false constructor: (@command, @params, @result) -> @obj = _(@obj).clonedeep() @obj.result = @result that example uses clonedeep lodash, there similar cloning tools in every utility belt javascript library.
Comments
Post a Comment