The first two days of writing a chrome extensions, because the content and background interaction will require an asynchronous method implementation, such as:
Copy Code code as follows:
var Test = new Class ({
Options: {},
Initialize:function (args) {
Chrome.extension.sendRequest ({' type ': ' Options '}, function (options) {
this.options = options;
......
});
}
});
This should be the object of test, but the callback method is empty. Do you want to pass this parameter and call back? Fortunately, MooTools has a good way to bind.
Copy Code code as follows:
var Test = new Class ({
Options: {},
Initialize:function (args) {
Chrome.extension.sendRequest ({' type ': ' Options '}, function (options) {
this.options = options;
......
}.bind (this));
}
});
This is OK, continue to write:
Copy Code code as follows:
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 what this is. And the real code is much scarier than this, and in some cases we really need this to point to other variables, not to this class.
The most common solution is this:
Copy Code code as follows:
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 specifically defined a _self variable to replace this, what does this look like? Python!
Now I finally realize that Python self is absolutely not superfluous.