JavaScript中的静态变量

本文翻译自:Static variables in JavaScript

如何在Javascript中创建静态变量?


#1楼

参考:https://stackoom.com/question/6RUF/JavaScript中的静态变量


#2楼

The closest thing in JavaScript to a static variable is a global variable - this is simply a variable declared outside the scope of a function or object literal: JavaScript中与静态变量最接近的是全局变量 - 这只是在函数或对象文字范围之外声明的变量:

var thisIsGlobal = 1;

function foo() {
    var thisIsNot = 2;
}

The other thing you could do would be to store global variables inside an object literal like this: 您可以做的另一件事是将全局变量存储在对象文字中,如下所示:

var foo = { bar : 1 }

And then access the variabels like this: foo.bar . 然后像这样访问变量: foo.bar


#3楼

窗口级变量就像静态一样,你可以使用直接引用,这些变量可用于应用的所有部分


#4楼

You might take advantage of the fact that JS functions are also objects -- which means they can have properties. 您可以利用JS函数也是对象的事实 - 这意味着它们可以具有属性。

For instance, quoting the example given on the (now vanished) article Static variables in Javascript : 例如,引用Javascript中的(现已消失的)文章静态变量给出的示例:

function countMyself() {
    // Check to see if the counter has been initialized
    if ( typeof countMyself.counter == 'undefined' ) {
        // It has not... perform the initialization
        countMyself.counter = 0;
    }

    // Do something stupid to indicate the value
    alert(++countMyself.counter);
}

If you call that function several time, you'll see the counter is being incremented. 如果您多次调用该函数,您将看到计数器正在递增。

And this is probably a much better solution than poluting the global namespace with a global variable. 这可能是一个比使用全局变量来规划全局命名空间更好的解决方案。


And here is another possible solution, based on a closure : Trick to use static variables in javascript : 这是另一个可能的解决方案,基于一个闭包: 在javascript中使用静态变量的技巧

var uniqueID = (function() {
   var id = 0; // This is the private persistent value
   // The outer function returns a nested function that has access
   // to the persistent value.  It is this nested function we're storing
   // in the variable uniqueID above.
   return function() { return id++; };  // Return and increment
})(); // Invoke the outer function after defining it.

Which gets you the same kind of result -- except, this time, the incremented value is returned, instead of displayed. 这会得到相同类型的结果 - 除此之外,返回递增的值而不是显示。


#5楼

There is no such thing as an static variable in Javascript. 在Javascript中没有静态变量这样的东西。 This language is prototype-based object orientated, so there are no classes, but prototypes from where objects "copy" themselves. 这种语言是基于原型的面向对象的,因此没有类,而是来自对象“复制”自身的原型。

You may simulate them with global variables or with prototyping (adding a property to the prototype): 您可以使用全局变量或原型来模拟它们(向原型添加属性):

function circle(){
}
circle.prototype.pi=3.14159

#6楼

If you come from a class-based, statically typed object-oriented language (like Java, C++ or C#) I assume that you are trying to create a variable or method associated to a "type" but not to an instance. 如果你来自基于类的,静态类型的面向对象语言(如Java,C ++或C#),我假设您正在尝试创建与“类型”相关但不与实例相关联的变量或方法。

An example using a "classical" approach, with constructor functions maybe could help you to catch the concepts of basic OO JavaScript: 使用“经典”方法的示例,使用构造函数可能可以帮助您捕获基本OO JavaScript的概念:

function MyClass () { // constructor function
  var privateVariable = "foo";  // Private variable 

  this.publicVariable = "bar";  // Public variable 

  this.privilegedMethod = function () {  // Public Method
    alert(privateVariable);
  };
}

// Instance method will be available to all instances but only load once in memory 
MyClass.prototype.publicMethod = function () {    
  alert(this.publicVariable);
};

// Static variable shared by all instances
MyClass.staticProperty = "baz";

var myInstance = new MyClass();

staticProperty is defined in the MyClass object (which is a function) and has nothing to do with its created instances, JavaScript treats functions as first-class objects , so being an object, you can assign properties to a function. staticProperty在MyClass对象(它是一个函数)中定义,与其创建的实例无关,JavaScript将函数视为第一类对象 ,因此作为对象,您可以为函数指定属性。

<think>我们正在讨论JavaScript中的类(class)的静态变量static variable)和私有变量(private variable)的区别及用法。 根据用户的问题,我们需要明确以下几点: 1. 静态变量static variable)是类级别的,属于类本身,而不是类的实例。它们通过`static`关键字定义。 2. 私有变量(private variable)是实例级别的,并且只能在类内部访问。它们通过`#`前缀(ES2022正式支持)或通过闭包(传统方式)实现。 我们将分别介绍静态变量和私有变量的定义、用法和区别,并给出代码示例。 注意:在JavaScript中,私有变量(使用#)是真正私有的,不能在类外部访问。而静态变量(使用static)是类本身的属性。 下面我们详细说明: ### 静态变量Static Variables) - 静态变量属于类本身,而不是类的任何实例。 - 使用`static`关键字在类内部声明。 - 可以通过类名直接访问,也可以通过类的静态方法访问,但不能通过类的实例访问(除非通过类名)。 - 通常用于存储与类相关的常量或与所有实例共享的数据。 ### 私有变量(Private Variables) - 私有变量属于类的每个实例,但只能在类内部访问。 - 使用`#`前缀声明(ES2022及以后),或者通过WeakMap和闭包模拟(旧方法)。 - 不能在类外部直接访问,包括实例也不能直接访问(除非通过类内部的方法)。 - 通常用于封装实例的内部状态,避免外部直接修改。 代码示例: ```javascript class MyClass { // 静态变量 static staticVariable = "I am static"; // 私有变量(使用#) #privateVariable; constructor(value) { this.#privateVariable = value; } // 静态方法 static staticMethod() { return `Static method: ${this.staticVariable}`; // 注意:在静态方法中,this指向类本身(MyClass) } // 实例方法,可以访问私有变量 getPrivate() { return this.#privateVariable; } } // 访问静态变量 console.log(MyClass.staticVariable); // "I am static" console.log(MyClass.staticMethod()); // "Static method: I am static" // 创建实例 let obj = new MyClass("Hello"); console.log(obj.getPrivate()); // "Hello" // 以下访问都会导致错误 // console.log(obj.#privateVariable); // SyntaxError: Private field '#privateVariable' must be declared in an enclosing class // console.log(obj.staticVariable); // undefined (因为静态变量不属于实例) ``` 在上面的例子中: - `staticVariable`是静态变量,通过`MyClass.staticVariable`访问。 - `#privateVariable`是私有变量,只能在类内部通过`this.#privateVariable`访问,外部无法直接访问。 另外,我们也可以使用静态私有变量(即静态且私有的变量),这可以通过在静态变量前加`#`来实现(但注意,静态私有变量也是ES2022的特性): ```javascript class MyClass { static #privateStaticVariable = "I am private static"; static getPrivateStatic() { return this.#privateStaticVariable; } } console.log(MyClass.getPrivateStatic()); // "I am private static" // console.log(MyClass.#privateStaticVariable); // 错误,无法在类外部访问 ``` ### 区别总结 | 特性 | 静态变量 | 私有变量 | |--------------|----------------------------------|----------------------------------| | 所属 | 类本身 | 类的实例 | | 访问方式 | 通过类名访问(`ClassName.var`) | 只能在类内部访问(使用`#`前缀) | | 存储位置 | 类(构造函数)上 | 每个实例内部 | | 共享性 | 所有实例共享 | 每个实例独立 | | 如何声明 | `static`关键字 | `#`前缀 | 希望这个解释和示例能帮助你理解。 如果用户有进一步的问题,我们可以生成相关问题。 §§相关问题§§ 1. 在JavaScript中,静态私有变量是如何声明的? 2. 除了使用`#`,还有哪些方法可以实现私有变量? 3. 静态方法中能否访问私有变量?为什么? 4. 私有变量和静态变量在继承中表现如何?</think>### JavaScript 类中静态变量与私有变量的区别及用法 #### **1. 静态变量 (Static Variable)** - **定义**:使用 `static` 关键字声明,属于类本身而非实例。 - **特性**: - 通过类名直接访问:`ClassName.staticVar` - 所有实例共享同一内存地址 - 常用于工具方法或全局配置 - **示例**: ```javascript class Config { static API_KEY = "abc123"; // 静态变量 static getBaseUrl() { // 静态方法 return "https://api.example.com"; } } console.log(Config.API_KEY); // "abc123"(直接通过类访问) ``` #### **2. 私有变量 (Private Variable)** - **定义**:使用 `#` 前缀声明,仅在类内部可访问。 - **特性**: - 每个实例拥有独立副本 - 外部直接访问会报错:`SyntaxError` - 需通过公共方法(如 getter/setter)间接操作 - **示例**: ```javascript class User { #id; // 私有变量 constructor(id) { this.#id = id; } // 公共方法访问私有变量 getUserId() { return this.#id; } } const user = new User(100); console.log(user.getUserId()); // 100 // console.log(user.#id); // 报错:Private field '#id' must be declared in an enclosing class ``` --- #### **核心区别对比** | **特性** | **静态变量** | **私有变量** | |------------------|----------------------------------|----------------------------------| | **作用域** | 类级别 | 实例级别 | | **访问方式** | `ClassName.staticVar` | 仅限类内部通过 `#var` 访问 | | **内存分配** | 所有实例共享同一内存 | 每个实例独立存储 | | **用途** | 全局配置/工具函数 | 封装敏感数据(如ID、密码) | | **语法** | `static var = value` | `#var = value` | --- #### **混合使用场景** ```javascript class Logger { static #logLevel = "DEBUG"; // 静态私有变量(类级别私有) static setLogLevel(level) { this.#logLevel = level; } static log(message) { console.log(`[${this.#logLevel}] ${message}`); } } Logger.setLogLevel("ERROR"); Logger.log("System crashed"); // [ERROR] System crashed // Logger.#logLevel; // 报错(外部不可访问) ``` --- #### **注意事项** 1. **浏览器兼容性**: - 私有变量 (`#`) 需 ES2022+ 或 Babel 转译 - 旧版 JS 可通过闭包模拟私有性(非真正私有): ```javascript function OldClass() { const privateVar = "secret"; // 闭包私有变量 this.getPrivate = () => privateVar; } ``` 2. **设计原则**: - 静态变量:减少全局污染,替代全局变量[^1] - 私有变量:强化封装性,避免外部意外修改[^2] 3. **静态私有变量**: - 声明:`static #var` - 作用:类级别私有数据(如内部配置) ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值