Wednesday 22 November 2017

prototype oriented - How to declare a static variable in Javascript





In the following code, I would like to have a counter to keep track
of the number of Person objects created. This code is not doing so, how would I
accomplish that?



function
Person(){
this.name = "Peter";
this.counter = this.counter +
1;

alert(this.counter);
}


Person.prototype.counter
= 0;

var p1 = new Person;
var p2 = new
Person;

class="post-text" itemprop="text">
class="normal">Answer




function Person(){

this.name = "Peter";
Person.counter++;

alert(Person.counter);

}

Person.counter =
0;

var p1 = new Person();
var p2 = new
Person();


Make the
"static" variable a property of the Person function, rather
than the prototype, and use Person
instead of this inside the
constructor.




This is possible because
JavaScript functions are first-class (i.e. they are objects), so can have properties of
their own.



Here's a href="http://jsfiddle.net/interdream/RhXPC/" rel="noreferrer">working
example of the above code.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...