0

I am trying to call a generic function but when that function is executed I am in a different scope (window). This code will picture the case:

Ext.application({
    name : 'Fiddle',
    context: null,

    function1 : function(){
        this.function2(this.function3);
    },

    function2 : function(func){
        func();
    },

    function3 : function(){
        if(context == this){
            Ext.Msg.alert('Fiddle', 'Same context!');
        }
        else {
            Ext.Msg.alert('Fiddle', 'Different context!');
        }
    },

    launch : function() {
        context = this;
        this.function1();
    }
});

I am trying to use bind but it is not working.

Thanks!

EDIT: I am so sorry guys, I said Javascript instead of Sencha. I thought the issue would be the same in Javascript and I could get more help. I apologise. I created a code in fiddle to replicate the issue. Thanks to all the comments and help, they are really appreciated!

JM. Benitez
  • 420
  • 1
  • 4
  • 9
  • 3
    Provide more code. The code you provided isn't even syntactically correct and will give a syntax error. – PitaJ Jun 09 '16 at 15:40
  • 1
    Functions can't lose their scope. What you mean is that the context on which they are called is unexpected. – Bergi Jun 09 '16 at 15:47
  • @FelixKling, PitaJ: I guess those functions are part of an object literal. – Bergi Jun 09 '16 at 15:49

1 Answers1

0

You can use the bind method to bind your context (this).

function1 : function(arg){
    this.function2(this.function3.bind(this), arg) // using bind
},

function2 : function(func, arg){
    func(arg);    // <-- Issue
},

function3 : function(arg){
    // this = window... I lost the scope??
},
bcr
  • 3,791
  • 18
  • 28
  • 1
    Since `function2` is called as a normal function `this` will also refer to `window` there as well. – Felix Kling Jun 09 '16 at 15:46
  • Ah, you're right. Editing my answer now. – bcr Jun 09 '16 at 15:48
  • @FelixKling It seems like this is being called in an object with the structure `var objName = { func1: function () {}, func2: function () {}, func2: function () {} }` but if that was the case the context should be the same in `func3`. I guess we need more info. – bcr Jun 09 '16 at 15:50
  • 1
    @FelixKling: It probably is `this.function2(…)` anyway – Bergi Jun 09 '16 at 15:51
  • Sorry guys, I corrected the code above. The issue is happening in Sencha but I thought it would be the same in Javascript and I ended up messing things up. – JM. Benitez Jun 09 '16 at 17:17
  • I will create a new question. This is quite a mess. Sorry for the inconvenience. – JM. Benitez Jun 09 '16 at 17:23