$.proxy()

作者: Rokkia | 来源:发表于2018-07-05 11:15 被阅读11次

$.proxy() 三个参数

  1. function 被调用的已有的函数
  2. context 函数所在的对象的名称
  3. name 已有的函数(应该是context的属性)

返回值
· 函数(这个函数是包含上下文对象的一个函数,执行该函数时,this只想该上下文对象)

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title> 
<script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    test=function()
    {
        this.txt="这是一个对象属性";
        $("div").click($.proxy(this.myClick,this));
        //$("div").click(this.myClick);
    };

    test.prototype.myClick = function(event)
    {
        alert(this.txt);
        alert(event.currentTarget.nodeName);
    };

    var x = new test();
});
</script>
</head>
<body>

<div>这是一个 div 元素。</div>

</body>
</html>

当我们使用.proxy()来传入this时, this被传入,这是this是test,调用this.text时,也会拿到。 但是不使用.proxy时this指向的是div。

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>菜鸟教程(runoob.com)</title>
    <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js">
    </script>
    <script>
        $(document).ready(function(){
            var objPerson = {
                name: "John Doe",
                age: 32,
                test: function(){
                    $("p").after("Name: " + this.name + "<br> Age: " + this.age);
                }
            };
            $("button").click($.proxy(objPerson, 'test'));
            // $("button").click(objPerson.test);
        });
    </script>
</head>
<body>

<button>执行 test 函数</button>
<p></p>

</body>
</html>

为什么要使用$.proxy(objPerson, 'test')是因为,直接使用的时候,test方法中的this是button。

这里也不难发现,当一个对象执行这个回调函数的时候,this会指向这个对象,即使这个函数是写在其他对象内的一个方法,this也将会指向这个方法调用它的那个对象。

相关文章

网友评论

      本文标题:$.proxy()

      本文链接:https://www.haomeiwen.com/subject/auwuuftx.html