SitePoint Sponsor

User Tag List

Results 1 to 17 of 17
  1. #1
    SitePoint Zealot SlaveToTheMan's Avatar
    Join Date
    Aug 2001
    Location
    Land of OZ
    Posts
    131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Object constructor syntax opinion?

    I recently ran across some code that looks like the following:
    Code JavaScript:
    //example 1
      var obj1 = new function () 
      {
          var i = 1;
        this.say = function (); 
        {
            alert(i);
        };
      };
     
      // call new object's say function
      obj1.say();
    It looks like example 1 is defining a class constructor and then immediately executing it using the new operator. The last line calls the obj1.say() and displays "1" to the screen in a browser.

    This seems like a confusing way to create an object using the new operator. Assuming the new operator is going to be used to create the object, then I would prefer the following because it seems more clear.
    Code JavaScript:
    //example 2
      var Obj2 = function()
      {
          var i = 5;
          this.say = function(){
              alert(i);
          };
      }
     
      // create a new object using the new operator
      // And assign it to the variable anotherObj
      var anotherObj = new Obj2();
      anotherObj.say();

    The advantages of example 2 are the following:

    • You have defined a class constructor which can be called many times over by calling new Obj2()
    • Example 1 is confusing and unclear. I work with many developers and it seems like example 1 could be misinterpreted. Example 2 is more clear and is a more commonly used way to create an object.
    • Even if you only need to create a single object, example 2 seems more clear.
    • Example 1 is too similar to the function constructor new Function()creating confusion

    Opinions?

    Have you ever seen the example 1 syntax before? Is it commonly used?

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Unless I had good reason too, which is difficult to come up with at this time, I'd be using the second method as well.

    I agree that first method is too easy to be misread as new Function()
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    We're from teh basements.
    Join Date
    Apr 2007
    Posts
    1,205
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This code should produce a syntax error because of the semicolon on line 5.

    Quote Originally Posted by SlaveToTheMan View Post
    Code JavaScript:
    //example 1
      var obj1 = new function () 
      {
          var i = 1;
        this.say = function (); 
        {
            alert(i);
        };
      };
     
      // call new object's say function
      obj1.say();
    That said, the intent of this code appears to be to make i a private member, i.e., a member variable that can only be accessed by a member function.

  4. #4
    SitePoint Evangelist bals28mjk's Avatar
    Join Date
    Aug 2007
    Posts
    405
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That's the case with example 2 as well though.

  5. #5
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    That's interesting, because I recall that eval.call() can be used to bust through such protection mechanisms
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  6. #6
    SitePoint Zealot SlaveToTheMan's Avatar
    Join Date
    Aug 2001
    Location
    Land of OZ
    Posts
    131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by World Wide Weird View Post
    This code should produce a syntax error because of the semicolon on line 5.
    Sure, may bad.

  7. #7
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I use object literals for my classes. I've found them to be a great benefit especially for large sites. One site i'm working on uses a core class (object literal) which exposes methods which dynamically load additional js files which extend the core class.

    i.e.

    Core.js
    Code js:
    var Core = {
     
        Library : {
     
            Load : function(name) {
     
                // load dynamic js document
     
            }
     
        }
     
    }

    test_library.js
    Code js:
    if(typeof(Core) == 'undefined') throw('Unable to access Core!');
     
    Core.Test = {
     
        AMethod : function() {
     
        },
        AProperty : true
     
    }

    That way I can do the following:

    Code js:
    Core.Library.Load('Test');
    Core.Test.AMethod();
    alert(Core.Test.AProperty);

    Also means that I only have to include one JS file and only when required will I load any additional libraries...

    Good or bad, I don't know but it certainly works for me.


  8. #8
    SitePoint Zealot SlaveToTheMan's Avatar
    Join Date
    Aug 2001
    Location
    Land of OZ
    Posts
    131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question

    Quote Originally Posted by gRoberts View Post
    I use object literals for my classes. I've found them to be a great benefit especially for large sites.
    Your load function is interesting. Using object literals, what do you do when you need to agree create an object over and over again? For example, a dog object, but you need to create Rover, Sam, and Ernie which are all new instances of the dog object.

    Everyone I work with are Java developers and therefore are used to class-based object oriented programming. Therefore I thought using the classical style JavaScript might be better. However, they need to be aware that JavaScript is not a class-based language and uses a prototype instead. There just seems to be trade-offs to either way (i.e., pseudoclassical or prototypal inheritance).

  9. #9
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    My way of doing it acts as a sort of namespace...

    You can then adapt that by doing:

    Code js:
    if(typeof(Core) == 'undefined') throw('Unable to access Core!');
     
    Core.Test = function() {
     
        return {
     
            AMethod : function() {
     
            },
            AProperty : true
     
        };
     
    }

    with

    Code js:
    Core.Library.Load('Test');
    var testInstance = new Core.Test();
        testInstance.AMethod();
    alert(testInstance.AProperty);


  10. #10
    SitePoint Zealot SlaveToTheMan's Avatar
    Join Date
    Aug 2001
    Location
    Land of OZ
    Posts
    131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    anyone ever seen this syntax used before from example 1?

  11. #11
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)


  12. #12
    SitePoint Zealot SlaveToTheMan's Avatar
    Join Date
    Aug 2001
    Location
    Land of OZ
    Posts
    131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    that's a good page. I didn't see where any of those examples used this syntax of "new function() {}". It used "new Function()" though but that's different.

  13. #13
    SitePoint Wizard gRoberts's Avatar
    Join Date
    Oct 2004
    Location
    Birtley, UK
    Posts
    2,439
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I can't say i've seen the exact syntax used before. Is there any point to this? Are you researching the best way to do something or are you just curious?


  14. #14
    SitePoint Zealot SlaveToTheMan's Avatar
    Join Date
    Aug 2001
    Location
    Land of OZ
    Posts
    131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I guess this answers my question which is "no that is not a commonly used syntax". It is very interesting though. You define an anonymous function that contains this making it a constructor function and then immediately execute it using the new operator which creates the object from the class and assigns it to a variable. Slick!

    I guess this is only helpful when producing a single object instance (singleton).

    In example 2, there is the line where you create the object using the new operator ...
    Code JavaScript:
    var anotherObj = new Obj2();
    anotherObj.say();
    If you accidentally didn't use the new operator and just called
    Code JavaScript:
    var anotherObj = Obj2();
    You would be in trouble because this now refers to the global object.

    Doing it like example 1 actually eliminates that issue. I guess if someone tried creating the obj1 without using the new
    Code JavaScript:
    var obj1 = function ()
    {
      var i = 1;
      this.say = function ()
      {
        alert(i);
      };
    };
     
    // call new object's say function
    obj1.say();
    Well, you'd be in the same spot creating say as a global variable.

  15. #15
    Guru in training bronze trophy SoulScratch's Avatar
    Join Date
    Apr 2006
    Location
    Maryland
    Posts
    1,838
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    example 1 is just a singleton pattern. another common way to create a private namespace would be self execute an anonymous function, it's not an object like the former. either way, it's not a common technique in ecmascript from what I've seen.

    you should check out pro js design patterns by apress if you haven't as it goes into many techniques not really known to most scripters

  16. #16
    SitePoint Zealot SlaveToTheMan's Avatar
    Join Date
    Aug 2001
    Location
    Land of OZ
    Posts
    131
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    i got the book, thanks

  17. #17
    SitePoint Wizard bronze trophy
    Join Date
    Jul 2008
    Posts
    5,757
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    My first thought was singleton. But it seems a poor way to do it, as you need to maintain the variables scope. But if scoping isn't an issue, seems cool.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •