为什么'this'不能在插件的功能内工作?

时间:2013-07-16 14:54:05

标签: jquery jquery-plugins

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

   var current = 5;
   function count(){

     this.text(current);

   }

    count();

 }
})(jQuery);

为什么在这个插件中我收到控制台错误Uncaught TypeError: Object [object global] has no method 'text'。  但是如果我将this声明为count函数之外的变量,  例如var this_selected = this;然后在count函数中使用它然后它正在工作。

2 个答案:

答案 0 :(得分:0)

在使用之前应声明javascript变量。在这种情况下,你不是指$(this)吗?

答案 1 :(得分:0)

this是Javascript的一个令人困惑和愚蠢的方面。任何不同意的人都在这个世界上花了太多时间。

您唯一能够真正了解函数this中的内容的方法有两种:

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

就我而言,问题已由dojo.hitch解决,apply在内部使用{{1}}。听起来这个解决方案在JQuery中有点不同。也许this answer会帮助你。

相关问题