Home > Web Front-end > JS Tutorial > Instructions on the use of this and self_javascript skills

Instructions on the use of this and self_javascript skills

WBOY
Release: 2016-05-16 18:22:01
Original
1570 people have browsed it

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:

Copy code The code is as follows:

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.
Copy code The code is 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 writing:
Copy code The code is 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 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:
Copy the code The code is 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 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.
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template