Instructions for the use of this and self _javascript tips

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.