3 ms·
Nice technique but it definitely illustrates the problems which Javascript's ill-defined this-keyword brings about (which was discussed here a few days ago). T
by trezor 15y ago
Nice technique but it definitely illustrates the problems which Javascript's ill-defined this-keyword brings about (which was discussed here a few days ago).
This same problem could easily have been solved by setting a private variable (self, _this, cx, whatever) to this upon instantiation and referring to that instead of this.
In fact, I find myself using that technique (using self-defined variables instead of context) , especially for namespacing.
var myNamespace = {};
(function(cx) {
cx.myClass = function() {
var self = this;
self.action = function() {
self.foo = "bar";
}
};
})(myNamespace);
It makes your code easier to refactor with fewer hard-references to maintain. I'm about to completely give up any usage of "this" for a "var self = this;" upon object-creation.
Javascript context-handling is really just too messed up to be dependent on, and while it allows for lots of "cute" hacks, I personally find it creating a lot more problems than it solves.