java - How to do Inner class object instantiaton with `new` Coffescript? -
in java, this:
public class world{ string name; world(string name){this.name = name;} public class worldobject{ string type; worldobject(string type){this.type = type;} string display(){ return type + " on " + name;} } //… public static void main(string[] args){ world w1 = new world("jo"), w2 = new world("kallisto"); worldobject sand = w1.new worldobject("sand"), rock = w2.new worldobject("rock"); system.out.println(sand.display()); system.out.println(rock.display()); } } i wanted emulate same, or similar, invocation syntax in coffeescript , ran anaesthetic formulations , asking simpler solutions.
first of, i'm pretty sure javascript doesn't allow nice inference of name java in case, please correct me if i'm wrong. figured i'd have go outer.name, that's of little concern. note program prints
sand on jo rock on kallisto as should resulting coffee scripts.
the simplest solution go factory method.but don't factory methods, because new keyword strong indicator create new object. that, if do, instantiation of worldobject different.
class world constructor: (@name) -> worldobjectfactory: (bar) -> new @worldobject(bar,@) worldobject: class @worldobject constructor: (@bar, @outer) -> display: ()-> "#{@bar} in #{@outer.name}" w1 = new world "jo" w2 = new world "kallisto" sand = w1.worldobjectfactory "sand" rock = w2.worldobjectfactory "rock" console.log obj.display() obj in [sand, rock] another variation be, "sneak in" outer object via defineproperty, looks ugly , messes things user might expect. furthermore, syntax still isn't want (but closest):
class world constructor: (@name) -> worldobjectfactory = (outer) -> class @worldobject constructor: (@bar) -> @outer = outer display: ()-> "#{@bar} in #{@outer.name}" object.defineproperty world.prototype, "worldobject", {get: ()-> worldobjectfactory @} w1 = new world "jo" w2 = new world "kallisto" sand = new w1.worldobject "sand" rock = new w2.worldobject "rock" console.log obj.display() obj in [sand, rock] is there way java's syntax (w1.new worldobject("sand"))? know how w1.new worldobject, "sand", exposes factory method outside world class.
and, if not, there way write second solution in more coffe-script ideomatic way? got more interested in coffeescript, might there nicer way write haven't come upon. (i haven't found coffeescript translation javascript's world.propotype = {…, worldobject(){…},…}, example).
Comments
Post a Comment