Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 249
LostCode Avatar asked Dec 20 '22 23:12

LostCode


1 Answers

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.

like image 81
go-oleg Avatar answered May 01 '23 15:05

go-oleg