0
(function($){
  $.fn.countdown = function(){

   var current = 5;
   function count(){

     this.text(current);

   }

    count();

 }
})(jQuery);

Why in this plugin I'm getting a console error Uncaught TypeError: Object [object global] has no method 'text'. But if i declare this as a variable outside of the count function, for example var this_selected = this; and then use it inside the count function then it is working.

1
  • scope question makes my head spin, I think this inside the count function refers to the window. I am sure someone will clear this up for you
    – Huangism
    Jul 16, 2013 at 14:58

2 Answers 2

0

A javascript variable should be declared before using it. Don't you mean $(this) in this case?

1
  • Not exactly. this outside the scope of the count function is already a jQuery object, therefore it doesn't need $(). Inside the count function it references window rather than the selected element, therefore $(this) isn't needed unless you want a jQuery object containing the window.
    – Kevin B
    Jul 16, 2013 at 15:24
0

this is a confusing and dumb aspect of Javascript. Anyone who disagrees has spent too much time in its world.

The only time you can really know what this will be in a function is in one of two ways:

myFunc = function() {
  // I wonder what 'this' is?
}
myObj.myFunc = myFunc;

myObj.myFunc();
// ('this' will be 'myObj')   ...OR...

myFunc.apply(myObj/*, any extra arguments here*/);
// ('this' will again be 'myObj'). apply is a special method in each function object

On my part, the issue is solved with dojo.hitch, which uses apply internally. It sounds like the solution is a little different in JQuery. Perhaps this answer will help you.

Your Answer

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

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