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.

user1906399
  • 753
  • 1
  • 13
  • 27
  • 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 '13 at 14:58

2 Answers2

0

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

Pieter
  • 1,823
  • 1
  • 12
  • 16
  • 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 '13 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.

Community
  • 1
  • 1
Katana314
  • 8,429
  • 2
  • 28
  • 36