www.webdeveloper.com
Results 1 to 2 of 2

Thread: public property defined in object is "undefined"?

  1. #1
    Join Date
    Aug 2012
    Posts
    2

    public property defined in object is "undefined"?

    I've got 2 javascript files, each is encapsulated in it's own namespace. I'll simplify to get to the issue I'm having. In the first file I've got:

    PHP Code:
    project.file1 = (function() {
        
    this.value 123;
    })(); 
    When I try to access the value in my 2nd file with project.file1.value I get "undefined". If I console.log(project.file1) in the 2nd file, it outputs the object and it's methods, but not the properties?

    PHP Code:
    project.file2 = (function() {
        
    //logs "undefined"
        
    console.log(project.file1.value);
    })(); 
    I'm thinking it's maybe something to do with file1 not being loaded/run before the 2nd one runs? I tried using modernizr to load all the js before the first method is called in file2, but that didn't seem to change anything. If I put a console.log(this.value) in file1 it outputs the correct value before the console.log in file2 outputs "undefined". Any idea what I might be doing wrong?

  2. #2
    Join Date
    Aug 2012
    Posts
    2

    Solved it!

    Of course it just took explaining the problem to send me on a tangent that solved my issue. Turns out I the variable wasn't accessible because I wasn't returning it. I ended up reading up on the "Module Pattern" which is what I was unknowingly using. Adding the following in my first file made it work as I was expecting.

    PHP Code:
    project.file1 = (function() {
         
    my = {};

         
    my.value 123;

        
    my.publicMethod methodName() {
           ...
        }

        return 
    my;
    })(); 

    I was returning my public methods before but not the public properties. All makes sense now!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

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



Recent Articles