为什么静态变量不显示输出

why static variable not show output?

本文关键字:显示 输出 变量 静态 为什么      更新时间:2023-09-26

我正在尝试创建静态变量和静态函数。但当我访问它时,它给了我不明确的原因?这是我的功能

  function Shape(){
        this.namev="naven"
        Shape.PIe="3.14";
        Shape.getName=function(){
            return "nveen test shhsd"
        }
    }
    alert(Shape.PIe)
    alert(Shape.getName())

您的Shape.getName()函数在第一次调用Shape()之后才会初始化(初始化代码在Shape()内部(,因此Shape.getName属性在调用Shape()之前不存在。

也许你想要的是:

// define constructor that should only be called with the new operator
function Shape() {
    this.namev="naven";
}
// define static methods and properties
// that can be used without an instance
Shape.PIe="3.14";
Shape.getName=function(){
    return "nveen test shhsd"
}
// test static methods and properties
alert(Shape.PIe)
alert(Shape.getName())

请记住,在Javascript中,函数是一个对象,它可以像普通对象一样拥有自己的属性。因此,在这种情况下,您只是将Shape函数用作一个对象,可以对其放置静态属性或方法。但是,不要期望在静态方法内部使用this,因为它们没有连接到任何实例。它们是静态的。


如果希望实例属性或方法能够唯一地访问Shape对象实例,则需要以不同的方式创建方法和属性(因为实例方法或属性不是静态的(。

要创建一个由所有实例共享的静态变量,您需要在函数声明之外声明它,如下所示:

function Shape() {
    // ...
}
Shape.PIe = "3.14";
alert(Shape.PIe);

有关如何将一些熟悉的OOP访问概念"翻译"为Javascript的更多详细信息,请参阅本文:https://stackoverflow.com/a/1535687/1079597