Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
259 views
in Technique[技术] by (71.8m points)

javascript - JavaScript中的静态变量(Static variables in JavaScript)

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

  ask by Rajat translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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将函数视为第一类对象 ,因此作为对象,您可以为函数指定属性。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...