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

Err*_*oid 0 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>
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 5

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

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

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

这条线foo.bar();做了三件不同的事情:

  1. barfoo对象中检索属性.
  2. 它调用属性引用的函数.
  3. 它以this引用的方式做#2 foo.

(更多信息:神话方法.)

所以在电话中

$('#test1').plugin.fun();
Run Code Online (Sandbox Code Playgroud)

...... 将this在内,因为我们正在通过财产打电话.funpluginfunplugin

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

$('#test1').draggable('disable');
Run Code Online (Sandbox Code Playgroud)

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

$('#test1').plugin('fun');
Run Code Online (Sandbox Code Playgroud)

更多关于函数调用:

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
Run Code Online (Sandbox Code Playgroud)

callapply调用一个函数,将this值设置为您传递给它们的第一个参数.call和之间的区别在于apply如何将参数传递给目标函数.有了call,你只需要为call函数添加更多参数; with 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
Run Code Online (Sandbox Code Playgroud)