Instantiate a standard global function to call functions

Asked

Viewed 403 times

1

I wonder how I can create a global variable (or global element, I don’t know what you call it) as in several plugins I see. Example in Jquery where to call any function related to it only have to instantiate the symbol # or call for the function Jquery before any internal function of the plugin.

I want my application to be able to call something like:

MeuElemento.Cria(args);
MeuElemento.Salvar(args);
MeuElemento.Outrafunção(args);

How do I do that? Can someone please give me an example?

1 answer

3


Just create a global object and add functions to it.

When you make a global object, as below, it becomes visible... Well, globally.

var foo = {}; // foo só será global se essa linha rodar no escopo global, ok?

Now just add functions or whatever else you want. You can do this at any time, as Javascript objects can receive new properties and methods dynamically.

foo.monstraUmPopup = function (args) {
    alert(args);
}

And you can call globally too:

foo.mostraUmPopup("tio");

Try it on your browser console.

  • I wouldn’t recommend omitting the var. Better use it by making sure that the variable is being declared in the overall scope. I find it less confusing.

  • thank you very much, it will be much more organized my code rs

  • @bfavaretto Do not use var forces the variable to stay in the global scope, but you’re right about being less confused with var. I’ll edit.

  • I know how strong it is, but I always recommend never to omit :) I already mentioned it here: http://answall.com/a/2517/74. PS: thanks for Edit

Browser other questions tagged

You are not signed in. Login or sign up in order to post.