Tag Archives: OOP

Losing “this” scope in JavaScript – Solution

Written by Garry Lachman (Admin). Filed under JavaScript. Tagged , , , , , , , , , , , . .

Hi….
When using Javascript as OOP mode deep functions (function in function) lose the “this” scope.
I found some solution for this problem…
Same problem i found when you call other class with callback, the callback function returns without “this” scope.

how the problem looks:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function scope_experiment() {
   
    this.test_var = "test";

    this.level_one = function() {
        alert("Level One: " + this.test_var);

        function level_two()    {
            alert("Level Two: " + this.test_var);
        }

        level_two();
    }
   
}

var test_scope = new scope_experiment();
test_scope.level_one();

The output will be:
1) Level One: test
2) Level Two: undefined

And now…. The solution:
All what you need is to pass “this” to the deep function…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function scope_experiment() {
   
    this.test_var = "test";

    this.level_one = function() {
        alert("Level One: " + this.test_var);

        function level_two(_this_scope) {
            // we use _this_scope as this
            alert("Level Two: " + _this_scope.test_var);
        }

        level_two(this); // we pass this to the function
    }
   
}

var test_scope = new scope_experiment();
test_scope.level_one();

The output will be:
1) Level One: test
2) Level Two: test

Mission Accomplished

Share