Coffeescript-Javascript correlation -


i trying understand how private methods created using coffeescript. following example code

class builders constructor: ->     // private method     call = =>             @priv2method()     // privileged method     privledgemethod: =>             call()     // privileged method      priv2method: =>             console.log("got it") 

following generated js code.

 

(function() { var builders, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; builders = (function() { var call, _this = this; function builders() { this.priv2method = __bind(this.priv2method, this); this.privledgemethod = __bind(this.privledgemethod, this); } call = function() { return builders.priv2method(); }; builders.prototype.privledgemethod = function() { return call(); }; builders.prototype.priv2method = function() { return console.log("got it"); }; return builders; }).call(this); }).call(this);

note have used "fat arrow" function definition. there couple of things didn't code.

  1. what's use of _this variable
  2. if run code : (new builders()).privledgemethod() inside call method doesn't find priv2method method. though builders object show priv2method property of it's prototype.

hopefully shed light here.

your call function not private method, there no such thing in javascript there no such thing in coffeescript.

a more accurate description of call be:

a function visible inside builders class.

defining call => creates behaves private class method. consider this:

class c     p = => console.log(@)     m: -> p()  c = new c c.m() 

if in console you'll see @ inside p class c itself, you'll see in console looks function that's coffeescript class is. that's why see var _this in javascript. when coffeescript sees => , you're not defining method, coffeescript uses standard var _this = this trick make sure references come out right in bound function.

also note call is, more or less, private class method there no builders instance , can't call instance method priv2method without builders instance.

your privledgemethod method:

privledgemethod: =>     call() 

will work fine because call function (not method), function happens bound class still function. hence lack of @ prefix when call(). if call proper class method:

@call: -> ... 

then you'd call class method in usual way:

@constructor.call() 

here's simple demo might clarify things: http://jsfiddle.net/ambiguous/tqv4e/


Comments

Popular posts from this blog

Change php variable from jquery value using ajax (same page) -

Pull out data related to my apps from Android Play Store and iOS App Store -

How can I fetch data from a web server in an android application? -