Joe Caraccio Joe Caraccio - 3 months ago 8
Javascript Question

Running Functions with Functions

I am trying to call functions within other functions

So if I do this it will work: all I am doing here is from my

SearchUpdater(text)
function calling the
Updater
function, and it works.

class Search2 extends React.Component {
constructor(props) {
super(props);

const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(['row 1', 'row 2']),
};
}

Updater(text){
var newArray = []
newArray.push(text)
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newArray),
});

}


SearchUpdater(text){


this.Updater(text)




}


However, if I want to run some functions within
SearchUpdater
(I have some complicated logic I want to put in.. makes it easier) it will say
this.updater
is undefined...

class Search2 extends React.Component {
constructor(props) {
super(props);

const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(['row 1', 'row 2']),
};
}

Updater(text){
var newArray = []
newArray.push(text)
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newArray),
});

}


SearchUpdater(text){

var ComplicatedLogicFunc = function(){
this.Updater("HEYO")

}
ComplicatedLogicFunc();



}


Any help would be great..
Thanks!

Answer

That's because this keyword in your inner function (var ComplicatedLogicFunc) is not referencing Search2 instance.

For this example, you could either use Arrow functions (which preserve the value of this):

var ComplicatedLogicFunc = () => {
    this.Updater("HEYO");
};

explicitly bind this keyword to the function call context:

ComplicatedLogicFunc.call(this);

or you could simply store your local context in another variable like this:

SearchUpdater(text) {
    var self = this;

    var ComplicatedLogicFunc = function(){
        self.Updater("HEYO")
    }

    ComplicatedLogicFunc();
}

You can read more about how this keyword works in JavaScript here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

Comments