I was writing a chrome extensions two days ago, because the interaction between content and background must be implemented by an asynchronous method, such as:
var Test = new Class({
options: {},
initialize: function(args) {
chrome.extension.sendRequest({ 'type ':'options' }, function(options) {
this.options = options;
...
});
}
});
This this should be the Test object, but it is empty in the callback method. Do we need to pass this as a parameter and then call it back? Fortunately, there is a good method in mootools, bind.
var Test = new Class({
options: {},
initialize: function(args) {
chrome.extension.sendRequest({ 'type':'options' }, function(options) {
this.options = options;
… …
}.bind(this));
}
});
This is OK, continue writing:
var Test = new Class({
options: {},
initialize: function(args ) {
chrome.extension.sendRequest({ 'type':'options' }, function(options) {
this.options = options;
$each(this.options, function(o, i ) {
if (o == '1') {
this.fun1();
} else {
this.fun2();
}
}.bind( this));
}.bind(this));
},
fun1: function {},
fun2: function {}
});
Even with bind, it’s not easy to tell which this is. The real code is much scarier than this. In some cases, we really need this to point to other variables instead of this class.
The most commonly used solution is this:
var Test = new Class({
options: {},
initialize: function(args) {
var _self = this;
chrome.extension.sendRequest({ 'type':'options' }, function(options) {
_self.options = options;
$each(_self.options, function(o, i) {
if (o == '1') {
_self .fun1();
} else {
_self.fun2();
}
});
});
},
fun1: function {},
fun2: function {}
});
I specially defined a _self variable to replace this. What does this look like? python!
Now I finally realize that python’s self is definitely not unnecessary.