【问题标题】:Why to use "this" for calling a function in jquery为什么在 jquery 中使用“this”来调用函数
【发布时间】:2012-02-20 05:49:04
【问题描述】:

我有以下代码。在下面的代码中,有两个函数调用另一个函数。但我不明白为什么一旦这个函数被这个函数调用,而另一个函数被另一个地方的变量调用。

 var widgetMethods = {

    getWidgetData: function($widgetElement) {

          var widgetData = $widgetElement.data('widgetData');

          widgetData = (typeof widgetData == 'undefined')  ? { type: null, key: null } : widgetData;

          if( widgetData.type == null ) {
            console.log("Widget type is not specified!");
            return false;
          }

          if( widgetData.key == null ) {
            console.log("Widget key is not specified!");
            return false;

          }
          return widgetData;
        },

    editWidget: function(key, options) {  

          var $self = jQuery(this);
          var widgetData = widgetMethods.getWidgetData($self);
          }

    getWidgetTemplate: function($widgetElement) {

          var widgetData = this.getWidgetData($widgetElement);
          }


    }

谁能帮帮我。我很迷惑。请简述。

【问题讨论】:

    标签: jquery oop jquery-ui


    【解决方案1】:

    this 指的是调用函数的元素的当前指针。因此,您可以使用“this”传递当前元素。但是,当您调用不由同一元素引用的不同函数时,您需要传递相同元素的属性才能使用它。

    如果您仍然感到困惑,请查看http://msdn.microsoft.com/en-us/library/y0dddwwd.aspx

    :)

    【讨论】:

    • 但是为什么我不能通过这个对象调用editWidget中的getWidgetData
    • 不要使用 $self... 使用 var self = $(this) 然后 var widgetData = widgetMethods.getWidgetData(self);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多