How to access from "private method" to "public variable", in Javascript class

First, see my plz code.

function test(){

    this.item = 'string';

    this.exec = function(){
        something();
    }

    function something(){
        console.log(this.item);
        console.log('string');
    }
}

And I made a class and called the exec function, like this code

var t = new test();

t.exec();

But the result ...

undefined
string

I want to access something from the test.item function.

Do you have a solution?

+4
source share
4 answers

You need to call somethingwith applyto thisbe properly installed inside something:

function test(){

    this.item = 'string';

    this.exec = function(){
        something.apply(this);
    }

    function something(){
        console.log(this.item);
        console.log('string');
    }
}

As @aaronfay noted, this is because it thisdoes not reference the object created new test(). You can read about it here , but the general rule is:

object, this object. ( ), this , window.

+6

, .

var item = 'string'

this.exec = function(){
    something.apply(this, []);
}

var that = this;
function something(){
    console.log(that.item);
    console.log('string');
}
+2

this.item something() - , .

this . .

, , this, .


function test() {
    var that = this; // a reference to 'this'

    function something() {
        console.log(that.item); // using the outer 'this'
        console.log('string');
    }

    this.item = 'string';

    this.exec = function(){
        something();
    }
}
+2

- :

Fiddle

function test(){

    this.item = 'string';

    this.exec = function(){
        this.something();
    }

    this.something = function(){
        console.log(this.item);
        console.log('string');
    }
} 

var t = new test();
t.exec();
// output:
// string 
// string
+1

All Articles