Loading ...
Sorry, an error occurred while loading the content.
 

Re: JavaScript Syntax

Expand Messages
  • dustindiaz
    Yes, the core reasoning behind self invoking a function and returning properties is to gain just that. You can add private methods to your class-like
    Message 1 of 4 , May 27, 2006
      Yes, the core reasoning behind self invoking a function and returning
      properties is to gain just that. You can add private methods to your
      "class-like" objects.

      And in complete honesty, it's really not that strange once you get
      used to it. the most strangest part about it is the self-invoking
      structure of it all..
      Eg:

      var foo = function(msg) {
      alert(msg);
      }('hello world');

      This will cause the function to run once it's defined, thus passing in
      a string 'hello world' and immediately alerting it. That is why we
      immediately return an object.

      However in the case of just doing something small, you rarely need to
      do it that way... especially when you have not a single private method
      and you're just showing an example.

      Regards,
      Dustin Diaz

      --- In ydn-javascript@yahoogroups.com, "louisarquie"
      <louis.arquie@...> wrote:
      >
      > Actually, I just found this link that may explain the syntax:
      > http://www.dustindiaz.com/namespace-your-javascript/
      >
      > Is the only benefit, for this strange syntax, to be able to add
      > private properties and methods in the future?
      >
      > Thanks,
      > Louis
      >
      > --- In ydn-javascript@yahoogroups.com, "louisarquie"
      > <louis.arquie@> wrote:
      > >
      > > Coming from a C++/Java background, I was really puzzled with the
      > > following syntax in yui/examples/dragdrop/list.html:
      > >
      > > YAHOO.example.DDApp = function() {
      > > return {
      > > init: function() {
      > >
      > > ...
      > >
      > > }
      > > };
      > > } ();
      > >
      > > YAHOO.util.Event.addListener(window, "load",
      YAHOO.example.DDApp.init);
      > >
      > > It took me a while to understand what's going on (I think I do now,
      > > but I am not 100% sure).
      > >
      > > Anyway, why is it written that way?
      > >
      > > Why not:
      > >
      > > YAHOO.example.DDApp = {
      > > init: function() {
      > >
      > > ...
      > >
      > > }
      > > };
      > >
      > > YAHOO.util.Event.addListener(window, "load",
      YAHOO.example.DDApp.init);
      > >
      > > Would not that do the same thing?
      > >
      > > Thanks,
      > > Louis
      > >
      >
    Your message has been successfully submitted and would be delivered to recipients shortly.