0

I am trying to create static variable and static function .But when I am accessing it it gives me undefined why ? here is my function

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

    }

    alert(Shape.PIe)
    alert(Shape.getName())
user944513
  • 12,247
  • 49
  • 168
  • 318
  • It doesn't make sense for `getName()` to be "static", because surely it should return the name property associated with a particular instance? I'd suggest you find a tutorial about JavaScript's prototype-based inheritance and then consider whether or not adding properties directly to `Shape` is the best way to go. – nnnnnn Jul 04 '15 at 06:02

2 Answers2

3

Your Shape.getName() function is not initialized until after Shape() has been called the first time (the initialization code is inside of Shape()) so thus the Shape.getName properties does not exist until Shape() is called.

Perhaps what you want is this:

// 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())

Remember that in Javascript a function is an object that can have it's own properties just like a plain object. So, in this case you're just using the Shape function as an object that you can put static properties or methods on. But, do not expect to use this inside of static methods because they are not connected to any instance. They are static.


If you want instance properties or methods that can uniquely access a Shape object instance, then you would need to create your methods and properties differently (since instance methods or properties are not static).

jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

To create a static variable shared by all instances, you would need to declare it outside of the function declaration, like so:

function Shape() {
    // ...
}

Shape.PIe = "3.14";

alert(Shape.PIe);

See this post for more details on how you can "translate" some familiar OOP access concepts into Javascript: https://stackoverflow.com/a/1535687/1079597

Community
  • 1
  • 1
cjm
  • 120
  • 2
  • 11