ETC
RSS Links
Tag Cloud
5.3 abstract actionscript actionscript3 Adapter adobe Advance ajax Anonymous Anonymous function apache Array array_walk article as as3 as3corelib Auth Base64 basics bind bitmap bug bytearray callback catch chart charts class cleanup client closures closures function CodeIgniter commerce communicate Communicator compiler console console.log controller crypto css custom event Decryption design patterns dialog dispatch div download Dwoo ecommerce editor Encode Encryption engine ereg ereg_replace error event example experiment explorer facebook Factory Factory Method file Flash Flash Media Server FMS Framework free function garry GNU GPL grchart hash link html ide ie ifconfig image insert internet explorer ip javascript jpeg jQuery jquery plugin js json lachman layer Layout Solution lib libary linux load local localhost log login manager MD5 MDB media microsoft Migrating Mime Type module modules mod_rewrite mvc mysql News Object Oriented old one time link one time url OOP Open Power Template open source oscommerce package pattern PEAR PEAR::Auth php php4 php5 php 5.3 phpclasses.org PHP Framework phpwebcommerce plugin PNG popup posfix POST preg_match preg_replace Presentation problem rect regex regexp request Requirements screen screen manager script select send server session shopping Shopping Cart singleton smarty Solution source code Specification sql ssh static STP table template templates this tooltip trigger try Tutorial UI update url User Interface users utf-8 util utils validate variables vi view vim virus warning widget window wordpress xml XTemplate yourinspirationweb
Losing “this” scope in JavaScript – Solution
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:
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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…
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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