The least habit of getting familiar with python is to add a self to every method. Whether Javascript or C #, you can do this directly. Why do you have to add a variable self. I wrote a chrome extensions two days ago, because an Asynchronous Method is required for interaction between content and background, for example:
The Code is as follows:
Var Test = new Class ({
Options :{},
Initialize: function (args ){
Chrome. extension. sendRequest ({'type': 'options'}, function (options ){
This. options = options;
......
});
}
});
This should be the Test object, but the callback method is empty. Do you want to pass this as a parameter and call back? Fortunately, there is a good method in mootools, bind.
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 ));
}
});
Now OK, continue to write:
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 is not easy to tell which this is. The real code is much more terrible than this one. In some cases, we do need this to point to other variables rather than this class.
The most common solution is as follows:
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 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 extra move.