javascript - CoffeeScript Object Property Pointing to the Same Object -
i have class use 2 separate objects. class has property myvar, object itself. should different each object. however, in instantiated objects myvar properties point same object, see code below. how can have unique/private myvar property each object?
class test myvar: {} obj = new test obj2 = new test obj.myvar['key'] = 'value' console.log obj.myvar # result: { key: 'value' } / correct console.log obj2.myvar # result: { key: 'value' } / incorrect! expected {}!
compiled javascript:
// generated coffeescript 1.6.3 (function() { var test, obj, obj2; test = (function() { function test() {} test.prototype.myvar = {}; return test; })(); obj = new test; obj2 = new test; obj.myvar['key'] = 'value'; console.log(obj.myvar); console.log(obj2.myvar); }).call(this);
update. have found possible "solution": put properties objects constructor, see below. there better solution?
class test constructor: -> @myvar = {}
no, there isn't better solution setting instance variables in constructor:
class test constructor: -> @myvar = {}
anything in class definition attached prototype they're shared instances else in prototype. quick @ javascript might helpful:
var test; test = (function() { function test() {} test.prototype.myvar = {}; return test; })();
you can safely put immutable things (such strings, numbers, , booleans) in class definition not mutable values. example, fine:
class c s: 'pancakes'
because way change s
replace completely:
c = new c c.s = 'house'
and shadows prototype value rather modifying it.
Comments
Post a Comment