你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对象实例的实例的属性或方法,那么你就需要创建的方法和属性不同(例如以来方法或属性不是静态的)。
getName()是“静态的”,因为它肯定会返回与特定实例关联的名称属性?我建议你找一个关于JavaScript的基于原型的继承的教程,然后考虑是否直接向'Shape'添加属性是最好的方法。 – nnnnnn