javascript - JavaScript 中的类变量

标签 javascript oop inheritance

我在尝试让类变量在 javascript 中工作时遇到了一些麻烦。

我以为我理解了原型(prototype)继承模型,但显然没有。我假设由于原型(prototype)将在对象之间共享,因此它们的变量也将共享。

这就是这段代码让我感到困惑的原因。

实现类变量的正确方法是什么?

function classA() {};

classA.prototype.shared = 0;

a = new classA;

//print both values to make sure that they are the same
classA.prototype.shared;
a.shared;

//increment class variable
classA.prototype.shared++;

//Verify that they are each 1 (Works)
classA.prototype.shared;
a.shared;

//now increment the other reference
a.shared++;

//Verify that they are each 2 (Doesn't Work)
classA.prototype.shared;
a.shared;

更新: 因此,似乎每个人都在确认这样一个事实:通过增加实例的变量,我们不会影响原型(prototype)。这很好,这就是我在示例中记录的内容,但这看起来不像是语言设计中的错误吗?为什么这种行为是可取的?我觉得很奇怪的是,当实例的 var 未定义时,我们按照原型(prototype)的隐藏链接获取 var 的值,但我们将其复制到实例对象中。

我也明白这不是java/c++/ruby/python,它是一种不同的语言。我只是好奇为什么这种行为可能是好的。

最佳答案

静态(类级别)变量可以这样完成:

function classA(){
    //initialize
}

classA.prototype.method1 = function(){
    //accessible from anywhere
    classA.static_var = 1;
    //accessible only from THIS object
    this.instance_var = 2;
}

classA.static_var = 1;  //This is the same variable that is accessed in method1()

由于 javascript 处理原型(prototype)的方式,您的输出看起来很奇怪。调用任何方法/检索实例化对象的变量首先检查实例,然后检查原型(prototype)。即

var a = new classA();
classA.prototype.stat = 1;

// checks a.stat which is undefined, then checks classA.prototype.stat which has a value
alert(a.stat); // (a.stat = undefined, a.prototype.stat = 1)

// after this a.stat will not check the prototype because it is defined in the object.
a.stat = 5;  // (a.stat = 5, a.prototype.stat = 1)

// this is essentially a.stat = a.stat + 1;
a.stat++; // (a.stat = 6, a.prototype.stat = 1) 

关于javascript - JavaScript 中的类变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/261219/

相关文章:

javascript - 向公众公开 Firebase apiKey 是否安全?

javascript - 居中布局,侧边栏扩展位于屏幕右侧

inheritance - 在需要将行为添加到List <>的情况下,使用组合而不是继承有什么优势?

ios - 选择泛化或关联(聚合)

java - 了解接口(interface)、类和继承的小型 UML 表示?

JavaScript JSON 比较

javascript - 了解 Backbone/Javascript 中的 "this"

c# - 在 OOP 中创建接口(interface)基础设施背后的哲学是什么?

python - 可以从嵌套类定义实现继承吗?

swift - 可以使用 Swift 中的实现者定义的功能扩展协议(protocol)吗?