I'm familiar with static and instance variables in java.
I can see javascript doesn't have the keyword 'static'
I can see that a function and the variables it can see outside of itself are rather like an object.
Experimenting at the javascript console, I see that
this.rrr= will create a variable outside the function, and if the function was called with new, then it creates an instance variable - a variable within the context of the object. Whereas if the function was called without new, then it just sets the variable outside of itself, there is no object, so it's essentially a static variable that it is setting.
Of course, no doubt as with java, (if I recall), an object can refer to a static variable, but a static method cannot refer to an instance variable. So if we call the function without 'new' then there's no instance variable for it to refer to. But if we call the function with new, then it should be able to refer to instance or static variables. And since in javascript it is possible to create variables outside of the function, it should perhaps be possible to create either instance variables or static variables.. I know that when the function is called without new, you can create a static variable. And when it's created with new, you can create an instance variable.. But can you also create a static variable when the function is created with new?
I set a variable rrr=1 it's essentially a static variable as it's not part of any object.
>rrr=1
1
I know that this.rrr could set an rrr variable within a p object, or could set a static rrr variable. And I know that the name asd() is superfluous and the function could be and may as well be anonymous.
>var p=function asd() {this.rrr=55;}
>p();
>rrr
55
>rrr=1
1
I can see that in the above, p() set the static variable rrr to 55 I then set rrr to 1 above
>rrr
1
>var q=new p();
>rrr
1
I know that q.rrr would have been set by the above.
>q=p();
>rrr
55
None of the above results surprise me. It's all as expected. But the examples clarify my question.
Is it possible, to call q=new p(); And have anything written in the p function, that sets the static rrr?
Like how an instance method in java can set a static variable, in java it does it by specifying the class name dot variable name, vs using 'this'. I wonder if javascript has a way?
this.rrr=55;inside your function does not really create a “static variable”, at least not if you mean that analog to what a static class property in Java would be.thissimply refers to the globalwindowobject, and thus you just createdwindow.rrr, so it it just a run-of-the-mill global variable. Had you just assigned a value torrrdirectly inside your function, the effect would have been the same …