How to access variables from a class using static methods?

//my class
function myClass()
{
   this.pubVar = 'hello public';
   var priVar = 'hello private';


}

myClass.staticMethod = function()
{

   //how do i access thos variables here

}

I tried alert(this.pubVar), and alert(priVar)without success. What am I doing wrong?

I will change the question a little. I did not explain this for the first time.

How to declare static variables in a class?

I know that with java it's simple, you just put a static infront of type variable and presto, you have a static variable. I can not find this parameter for javascript ..

+3
source share
5 answers

Definition:

myClass.staticMethod = function(obj)
{
    alert(obj.pubVar);
}

Using:

var instance = new myClass();
myClass.staticMethod(instance);

You cannot use "priVar" since it is not a class variable. This is a scope variable.

Also, if you need to access class properties, why are you making it a static method?

+3

, , , , , .

prototype:

function MyClass() {
   this.pubVar = 'hello public';
   var priVar = 'hello private';
}

MyClass.prototype.myMethod = function() {
   alert(this.pubVar);
}


var instance = new MyClass();
instance.myMethod(); // alerts 'hello public'

-, , , , new.

, , (this ).

+3

, , -

, .

//my class
function myClass()
{
   this.pubVar = 'hello public';
   var priVar = 'hello private';
}

myClass.staticProperty = 'someValue';

myClass.staticMethod = function()
{
    //This is how you access it
    alert(myClass.staticProperty);
}
+1

... "this", . - , "this" .

, - :

function myClass()
{
    this.pubVar = 'hello public';
    var priVar = 'hello private';

    this.method = function(){
        alert(priVar);
    }
}

, :

function myClass()
{
    this.pubVar = 'hello public';
    var priVar = 'hello private';
}
myClass.staticMethod = function(obj)
{
    alert(obj.pubVar);
}

,

0

. :

//my class
function myClass()
{
   this.pubVar = 'hello public';
   var priVar = 'hello private';
}

myClass.staticMethod = function()
{
   //how do i access thos variables here
   alert(this.pubVar);
}

var instance=new myClass(); // this is instance of class
myClass.staticMethod.call(instance)

, ? priVar. .

0

Source: https://habr.com/ru/post/1715457/


All Articles