arman
arman

Reputation: 125

what difference between directly return'this' and indirectly return 'object'? when creating jQuery plugin

i created one jQuery plugin

(function($) {
    'use strict';

    $.fn.charCount = function() {

return this.each(function(index,element){
  $(element).keyup(function updateCharCounter() {
        var $me = $(this),
            maxLength = parseInt($me.attr('maxlength'), 10),
            charCount = $me.val().length,
            $counter = $me.siblings('.limit');

        $counter.text('limit: ' + maxLength + ' characters. remainig: ' + (maxLength - charCount));

    });
});

    }
}(jQuery));

above code it's ok and work because i directly return this object

but when i change code to indirect object plugin does not work

(function($) {
    'use strict';

    $.fn.charCount = function() {
$oThis=this;
$oThis.each(function(index,element){
  $(element).keyup(function updateCharCounter() {
        var $me = $(this),
            maxLength = parseInt($me.attr('maxlength'), 10),
            charCount = $me.val().length,
            $counter = $me.siblings('.limit');

        $counter.text('limit: ' + maxLength + ' characters. remainig: ' + (maxLength - charCount));

    });
 });
 return $oThis;
    }
}(jQuery));

you can watch this plugin :https://jsfiddle.net/djary/yo6nLmzg/3/ what difference between directly and indirect return this

why in this case return this.each is work but $oThis not work? Where is wrong?

Upvotes: 0

Views: 20

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337627

If you check the console you can see the error is $oThis is not defined. This is because you specified use strict. That means that all variable definitions must be prefixed with var - as is good practice. You cannot be lazy and let the JS engine define the variable to the highest scope for you.

To fix the issue just use var $oThis = this;

Working example

Also note that I fixed the typo: remainig should be remaining.

Upvotes: 2

Related Questions