javascript - Making sense of class extension and instance properties in Coffee Script -


i've gotten coffee script , having issues figuring out how class extension works. seems properties defined instance properties on parent class being implemented static properties when class extended.

i have class, called foo, want use base class 2 sub classes, bar , goo. give foo instance property called foobs , method adding foob, so:

class foo     foobs:[]     addfoob: (foob) ->         @foobs.push(foob) 

and extend foo bar , goo, , create new instances, so:

class bar extends foo     othermethod: ->         alert 'doing other stuff'  class goo extends foo     secondmethod: ->         alert 'doing second stuff'  barinstance = new bar() gooinstance = new goo() 

but when add foob barinstance, gets added gooinstance!

barinstance.addfoob('test')  console.log gooinstance.foobs (outputs ["test"]) 

clearly i'm doing wrong here. want barinstance , gooinstance each have own "foobs" property, reason seems though foobs instance property on foo, it's getting assigned class property on bar , goo. ideas on how around this? or maybe there's different syntax i'm unaware of?

thanks

the problem how declaring foobs - want on instance, , should declared in constructor function. @ moment declared on prototype shared instances. if @ you're foo declaration compiles to, can see case:

class foo   foobs:[]   addfoob: (foob) ->     @foobs.push(foob) 

compiles to:

var foo = (function() {   function foo() {}   foo.prototype.foobs = [];   foo.prototype.addfoob = function(foob) {     return this.foobs.push(foob);   };   return foo; })(); 

what want declare constructor this:

class foo   constructor: (@foobs = [])->        addfoob: (foob) ->     @foobs.push(foob) 

which add foobs array each instance of foo.


Comments

Popular posts from this blog

android - getbluetoothservice() called with no bluetoothmanagercallback -

sql - ASP.NET SqlDataSource, like on SelectCommand -

ios - Undefined symbols for architecture armv7: "_OBJC_CLASS_$_SSZipArchive" -