LostCode
LostCode

Reputation: 533

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

First, See my code plz.

function test(){

    this.item = 'string';

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

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

And I made class and call 'exec function', like this code

var t = new test();

t.exec();

But result is...

undefined
string

I wanna access from something function to test.item.

Have you any solution?

Upvotes: 4

Views: 1481

Answers (4)

d.raev
d.raev

Reputation: 9546

Why not just define something like this:

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

Upvotes: 1

Joe Simmons
Joe Simmons

Reputation: 1848

this.item in something() isn't what you think it is.

The this value is different. In this case, it's the global object.

The best solution, in my opinion, is to declare a variable with a reference to this, that can be accessed inside the inner function.


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();
    }
}

Upvotes: 2

go-oleg
go-oleg

Reputation: 19480

You need to call something with apply so that this is properly set inside of something:

function test(){

    this.item = 'string';

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

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

As @aaronfay pointed out, this happens because this doesn't refer to the object that new test() created. You can read more about it here, but the general rule is:

If a function is invoked on an object, then this refers to that object. If a function is invoked on its own (as is the case in your code), then this refers to the global object, which in the browser is window.

Upvotes: 6

Chokchai
Chokchai

Reputation: 1722

You have many choices, but I recommend the last one.

var item = 'string'

or

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

or

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

Upvotes: 2

Related Questions