SoFunction
Updated on 2025-04-11

Instructions for using this and self

Two days ago, I was writing a chrome extension because the content must be used to interact with the background, such as:
Copy the codeThe code is as follows:

var Test = new Class({
options: {},
initialize: function(args) {
({ 'type':'options' }, function(options) {
= options;
……
});
}
});

This this should be the Test object, but the callback method is empty. Do you need to pass this as a parameter and then call it back? Fortunately, there is a good way in mootools, bind.
Copy the codeThe code is as follows:

var Test = new Class({
options: {},
initialize: function(args) {
({ 'type':'options' }, function(options) {
= options;
……
}.bind(this));
}
});

Now it's OK, continue writing:
Copy the codeThe code is as follows:

var Test = new Class({
options: {},
initialize: function(args) {
({ 'type':'options' }, function(options) {
= options;
$each(, function(o, i) {
if (o == '1') {
this.fun1();
} else {
this.fun2();
}
}.bind(this));
}.bind(this));
},
fun1: function {},
fun2: function {}
});


Even if there is a bind, it is not easy to tell which this is what. The real code is much more terrifying than this. In some cases, we do need this to point to other variables instead of this class.
The most commonly used solution is:
Copy the codeThe code is as follows:

var Test = new Class({
options: {},
initialize: function(args) {
var _self = this;
({ '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 variable of _self to replace this, what does this look like? python!
Now I finally realized that python's self is definitely not an unnecessary move.