简体   繁体   中英

Accessing global function variables in Javascript

Somehow I thought you could define a function as a global variable and access its internal variables. Example:

var func = function(){
    var connected = true;
}

console.log(func.connected);

However, this still comes up as "undefined". I thought it would be interesting to "namespace" certain variables like this.

I don't want to use objects/lists/dictionaries (how you prefer to call them) because you can delete those elements.

This is not possible.
In fact, it doesn't even make sense.
Each call to a function produces a separate set of local variables.

You should use objects to create namespaces, even though you can delete them.

If you want to, you can also make a class:
Note that you need to make an instance of the class:

function MyClass() { 
    this.connected = true;
}

var myInstance = new MyClass();
console.log(myInstance.connected);

However, you should not use classes to create singleton namespaces; there is no point.

Instead, you should write

var myNamespace = { connected: true };

console.log(myNamespace.connected);

var inside a function makes it private. use this.connected = true to make it public.

var func = function(){
    this.connected = true;
}

PS - As far as I know, all properties of an object are deletable unless they're non-enumerable, which I don't think you can easily specify. You should use this.connected even though it is deletable.

There is a good readup here on public/private methods and "privileged" methods.

EDIT: I assumed you knew about instantiating.. anyway just do x = new func to create an instance, then x.connected .

by using var it is private.

use it like this:

var func = function(){
    this.connected = true;
}
var namespace = new func();

console.log(namespace.connected);

remember that it needs to be instantiated.

You can use JSON notation like this:

var func = {
   connected:true,
   func:function(){
     func.connected = true;
   }
}
console.log(func.connected);
var MyClass = function() {
    function clazz() {
        this.message = "Hello"; //instance variable
    }

    clazz.connected = true; //static variable

    return clazz;
}();


alert(MyClass.connected)
alert(new MyClass().message)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM