我是谁 - JQuery,插件,$ this,$(this),这个,访问变量

时间:2010-12-30 14:03:31

标签: jquery plugins this

我在识别运行函数的对象

时遇到问题
<div id="test1">lorem</div>
<div id="test2">ipsum</div>

<script type="text/javascript">
    $(document).ready(function() {
        $('#test1').plugin(); //alert: I am test1
        $('#test2').plugin(); //alert: I am test2

        $('#test1').plugin.fun(); //alert: I am undefined and I am undefined
        $('#test2').plugin.fun(); //alert: I am undefined and I am undefined
    });
    (function($) {
        $.fn.plugin = function() {
            $this = $(this);
            alert('I am '+$(this).attr('id'));//<-- it works
        }
        $.fn.plugin.fun = function() {
            alert('I am '+$(this).attr('id')); //<-- doesn't work!
            alert('and I am '+$this.attr('id')); //<-- also doesn't work!
        }
    })(jQuery);
</script>

2 个答案:

答案 0 :(得分:5)

要了解$('#test1').plugin.fun();正在做什么,我们必须了解如何在JavaScript函数中设置this。我们将从理论开始,然后回到您的插件。

在JavaScript中,this完全由如何调用函数定义。最常见的方法是将其设置为从对象属性调用函数的副产品:

var foo = {
    msg: "I'm foo!",
    bar: function() {
        alert(this.msg);
    }
};
foo.bar(); // alerts "I'm foo!"

该行foo.bar();做了三件不同的事情:

  1. 它从bar对象中检索foo属性。
  2. 它调用属性引用的函数。
  3. 它以this引用foo
  4. 的方式排在第2位

    (更多信息:Mythical Methods。)

    所以在通话中

    $('#test1').plugin.fun();
    
    this中的

    ... fun将为plugin,因为我们通过fun上的媒体资源plugin

    您可以考虑使用jQuery UI使用的机制,即通过main函数访问插件的“方法”,名称为字符串。例如,在jQuery UI Draggable实例上,您可以调用以下方法:

    $('#test1').draggable('disable');
    

    有关更多示例,请参阅他们的Draggable documentation,但基本上您的调用将如下所示:

    $('#test1').plugin('fun');
    

    有关函数调用的更多信息:

    调用函数时还有另一种设置this的方法:通过函数实例上的callapply函数:

    var f = function() {
        alert(this.msg);
    };
    var foo = {
        msg: "I'm foo!"
    };
    f.call(foo);  // alerts "I'm foo!"
    f.apply(foo); // alerts "I'm foo!" too
    

    callapply调用一个函数,将this值设置为传递给它们的第一个参数。 callapply之间的区别在于如何将参数传递给目标函数。使用call,您只需向call函数添加更多参数;使用apply,您将一组参数作为apply的第二个参数。例子:

    function f(arg1, arg2) {
        alert(this.msg + " (" + arg1 + ", " + arg2 + ")");
    }
    var foo = {
        msg: "I'm foo!";
    };
    f.call(foo, "one", "two");    // Alerts "I'm foo! (one, two)"
    //          ^-- "one" and "two" are discrete arguments
    f.apply(foo, ["one", "two"]); // Alerts the same thing
    //           ^------------^-- "one" and "two" are in an array
    

答案 1 :(得分:1)

fun函数与您在调用中使用的对象没有任何直接关系,因此this只是window对象。

当您使用$('#test1').plugin时,您会获得对该函数的引用,并从中访问函数fun,但您获得的只是一个常规函数。您也可以使用$.fn.plugin.fun来获取函数,一旦获得对fun函数的引用,使用带有选择器的jQuery对象就没有任何相关性。

在调用fun函数之前,jQuery对象实际上会被丢弃,因此无法从函数中获取它。

相关问题