Take the 2-minute tour ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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:

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

to change element class or text content. Is this a good or efficient way to code?

share|improve this question

2 Answers 2

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);
   // ...
 }, 
 // ... 
share|improve this answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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