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
Anonymous functions now available from PHP 5.3
Anonymous functions, also known as closures, allow the creation of functions which have no specified name. They are most useful as the value of callback parameters, but they have many other uses.
Example:
2
3
4
{
echo "My name is $name";
};
Or you can use it as callback like javascript
2
3
4
5
6
7
8
9
10
11
12
"first_name" => "Garry",
"last_name" => "Lachman",
"age" => "27"
);
$callback_function = function ($field, $field_value)
{
echo "$field = $field_value";
};
array_walk($arr, $callback_function);
Using variables out function scope
2
3
4
5
6
7
8
9
10
11
12
13
14
$arr = array(
"first_name" => "Garry",
"last_name" => "Lachman",
"age" => "27"
);
$callback_function = function ($field, $field_value) use ($prefix)
{
echo "$prefix $field = $field_value";
};
array_walk($arr, $callback_function);
Have fun boys & girls