3
\$\begingroup\$

I'm creating a chat UI with jQueryUI:

$.widget("ui.chatwindow", {
    options: {
        nickname: "obama";
    },
    setNickname: function(nick){
        var self = this;
        var id_pre = 'wchat_' + self.options.nickname;
        $('#' + id_pre + '\\:name').text(self.options.nickname);
    },
    setStatus: function(status){
            var self = this;
            var id_pre = 'wchat_' + self.options.nickname;
            switch(status){
                case 1:
                    $('#' + id_pre + '\\:status').removeAttr('class');
                    $('#' + id_pre + '\\:status').addClass('chat-icon-online');
                    $('#' + id_pre + '\\:status').attr('title','Online');
                    break;
                    ...
                default:
                    break;                    
            }
            ...
        },
    ...
}

I always write this in every method to change element class or text content:

var self = this;
var id_pre = 'wchat_' + self.options.nickname;

Is this a good or efficient way to code?

\$\endgroup\$

2 Answers 2

2
\$\begingroup\$

I can't say there's anything technically wrong with doing it that way, and maybe some people who are only familiar with "self" in certain languages will get the point, but I think "this" is just as readable, and it saves you some code (along with some of us wondering where in the world "self" was defined if we're looking at a lot of code where the declaration isn't obvious).

So short of adding some extra work for yourself (and raising a couple of eyebrows), I don't see a big problem with it. Do you need it? No. Will it hurt? Not likely.

\$\endgroup\$
2
\$\begingroup\$

I completely agree with Kerri, but there is one good reason one may do this, namely if you need to reference your widget inside a closure or other anonymous function.

Example:

 // ...
 setStatus: function(status) {
    var self = this;
    window.setTimeout(function() {
       // If you try to access "this" here, if will no longer 
       // be referring to your widget. You have to use your 
       // variable "self" here.
    }, 1000);
   // ...
 }, 
 // ... 
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.