Hi, i'm creating chat ui with JQueryUI.
here some code:

$.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;                    
            }
            ...
        },
    ...
}

My Question is i always write 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?
let me know the good and efficient way to do this.

thanks for your kind.

share|improve this question

2 Answers

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

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

Your Answer

 
or
required, but never shown
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.