如果您来自基于类的静态类型的面向对象语言(like Java, C++ or C#),我假设您试图创建与"类型"关联的变量或方法,而不是与实例关联的变量或方法.
一个使用"classic "方法和构造函数的示例可能会帮助您理解基本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将函数视为first-class objects,因此作为一个对象,可以为函数分配属性.
UPDATE:ES6通过class
关键字引入了到declare classes的能力.它是现有的基于原型的继承之上的语法糖.
允许您轻松地在类中定义静电属性或方法.
让我们看看上面使用ES6类实现的示例:
class MyClass {
// class constructor, equivalent to
// the function body of a constructor
constructor() {
const privateVariable = 'private value'; // Private variable at the constructor scope
this.publicVariable = 'public value'; // Public property
this.privilegedMethod = function() {
// Public Method with access to the constructor scope variables
console.log(privateVariable);
};
}
// Prototype methods:
publicMethod() {
console.log(this.publicVariable);
}
// Static properties shared by all instances
static staticProperty = 'static value';
static staticMethod() {
console.log(this.staticProperty);
}
}
// We can add properties to the class prototype
MyClass.prototype.additionalMethod = function() {
console.log(this.publicVariable);
};
var myInstance = new MyClass();
myInstance.publicMethod(); // "public value"
myInstance.additionalMethod(); // "public value"
myInstance.privilegedMethod(); // "private value"
MyClass.staticMethod(); // "static value"