gpt4 book ai didi

javascript - JavaScript 中的类变量

转载 作者:行者123 更新时间:2023-12-02 23:29:39 25 4
gpt4 key购买 nike

我在尝试让类变量在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com