0

So I've got an object, or array, declared at the beginning of anything, outside everything:

var Thing = {title:'horse'};

Then I've got:-

$('.clickedIt').fadeOut(200, function() { console.log(Thing.title); }

That will fail. However, if I place above that same console log out of fadeOut, it'll be fine.

2
  • 1
    How does it fail? Where is the fadeOut called with respect to Thing? Commented Aug 17, 2012 at 15:54
  • 1
    can you provide a more complete script for us to look at? The problem here will laregely depend on the scope of Thing. Commented Aug 17, 2012 at 15:55

2 Answers 2

4

If you want something to be global, just define it on the window Object.

window.Thing = { title: 'horse '};

Then use it like so:

$( '.clickedIt' ).fadeOut(200, function() { 
    console.log( window.Thing.title ); 
});

Just a note, putting a number of variables on the window Object is not recommended, I would recommend looking into name-spacing: http://addyosmani.com/blog/essential-js-namespacing/

Here is an example:

//simple JavaScript module
( function( window ) {
    //define your applications root namespace
    window.myApp = {
        Thing: { title: 'horse '}
    };
})( window );

//jQuery ready function
$( function() {
    $( '.clickedIt' ).fadeOut( 200, function() { 
        console.log( myApp.Thing.title ); 
    });
});
Sign up to request clarification or add additional context in comments.

Comments

1

The value you assigned to title horse is undefined wrap it within quotes to make it string litral,

Live Demo

var Thing = {title:'horse'};
$('.clickedIt').fadeOut(200, function() { console.log(Thing.title); })​

5 Comments

I didn't downvote, but the OP stated that it does work with the console.log put outside, so horse is not the issue.
It appeared as though you had just copy and paste the question. I see your alteration now you explain, but that was a typed demo, so it's not the issue.
I checked on fiddle it gave me error for horse undefined @pimvdb
Yes, you solved another question, understandably... hence the down vote was reversed. Thanks.
I solved this question check the accepted answer that also wrapped horse within quotes. I could not exactly understand what you mean?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.