JavaScript中的静态变量 [英] Static variables in JavaScript

查看:178
本文介绍了JavaScript中的静态变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I create static variables in Javascript?

推荐答案

如果您来自基于类的静态类型对象 - 面向语言(如Java,C ++或C#)我假设您正在尝试创建与类型相关但不与实例相关联的变量或方法。

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.

使用经典方法的示例,使用构造函数可以帮助您捕获基本OO JavaScript的概念:

An example using a "classical" approach, with constructor functions maybe could help you to catch the concepts of basic 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 在MyClass对象中定义(这是一个函数)并且与其创建的实例无关,JavaScript将函数视为一等对象,因此作为对象,您可以为函数指定属性。

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.

这篇关于JavaScript中的静态变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆