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将函数视为第一类对象 ,因此作为对象,您可以为函数指定属性。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…