简体   繁体   English

在JavaScript中访问全局函数变量

[英]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". 但是,它仍然显示为“ 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. 我不想使用对象/列表/字典(您更喜欢称呼它们),因为您可以delete这些元素。

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. 即使可以delete对象,也应使用对象创建名称空间。

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. 函数内部的var使其变为私有。 use this.connected = true to make it public. 使用this.connected = true将其公开。

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. PS-据我所知,对象的所有属性都可以删除,除非它们是不可枚举的,我认为您不能轻易指定。 You should use this.connected even though it is deletable. 即使它是可删除的,也应使用this.connected

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 . 编辑:我以为您知道有关实例化..无论如何只是做x = new func创建一个实例,然后x.connected

by using var it is private. 通过使用var是私有的。

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: 您可以这样使用JSON表示法:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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