Maturano
Maturano

Reputation: 1023

Creating a javascript object Using object initializers

I'm kind a new in Javascript and I have this situation: I have a separated javascript file and I created a javascript object in this way:

$(document).ready(function () {    
    var formasPagamento = {
        Cartao: 0,
        Crediario: 1,
        Vale: 2
    };
});

In this same file, I have a function and I want to use this object formasPagamento, but when I try to use it, I get the error that formasPagamento is undefined.

Ex:

function CarregarDetalhesPlanoPagamento(idPosDocPagamento) {    
     if(idPosDocPagamento == formasPagamento.Cartao){ //undefined here
         //do something
     }
}

What's the proper way to initializa a "global" variable that can be used in another function?

Upvotes: 0

Views: 55

Answers (4)

This article explains it quite well w3School But basically the variable formasPagamento is only accessible inside the function scope of the document ready function.

$(document).ready(function () {
    var formasPagamento {};
    // CAN access here!
}
// CANNOT access here!

Upvotes: 1

Joe
Joe

Reputation: 170

Don't wrap var formasPagamento inside of $(document).ready. That is placing it inside of a child scope of global, making it inaccessible from your function. $(document).ready is to detect when the DOM is ready to be manipulated and there's no reason to postpone declaring that value.

Upvotes: 1

Andrew Burns
Andrew Burns

Reputation: 309

In your example, you're declaring formasPagamento inside the document.ready jQuery wrapper, so formasPagamento can only be accessed from within that function.

This is known as scope.

To be able to access formasPagamento globally, you can declare it before your $(document).ready.. like so:

var formasPagamento = {
    Cartao: 0,
    Crediario: 1,
    Vale: 2
};

$(document).ready(function () {    
   ..page ready logic..
});

Now when you use your function, it'll be able to see formasPagamento

Upvotes: 1

jl_
jl_

Reputation: 5539

What's the proper way to initializa a "global" variable that can be used in another function?

window.formasPagamento = {
    Cartao: 0,
    Crediario: 1,
    Vale: 2
};

Upvotes: 1

Related Questions