2015-07-04 33 views
0

我想创建静态变量和静态函数。但是当我访问它时,它给了我undefined为什么? 这里是我的功能为什么静态变量不显示输出?

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

    } 

    alert(Shape.PIe) 
    alert(Shape.getName()) 
+0

getName()是“静态的”,因为它肯定会返回与特定实例关联的名称属性?我建议你找一个关于JavaScript的基于原型的继承的教程,然后考虑是否直接向'Shape'添加属性是最好的方法。 – nnnnnn

回答

3

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对象实例的实例的属性或方法,那么你就需要创建的方法和属性不同(例如以来方法或属性不是静态的)。

+0

解决方案是什么? – user944513

+0

@ user944513 - 将代码添加到答案中。 – jfriend00

1

要建立由所有实例共享一个静态变量,你需要声明它的函数声明之外,像这样:

function Shape() { 
    // ... 
} 

Shape.PIe = "3.14"; 

alert(Shape.PIe); 

看到这个职位的详细信息,你如何能“翻译”一些将熟悉的OOP访问概念转换为Javascript:https://stackoverflow.com/a/1535687/1079597

相关问题