$.proxy的使用

来源:互联网 发布:sqlserver 字段默认值 编辑:程序博客网 时间:2024/06/06 03:16

1、$.proxy 方法接受一个已有的函数,并返回一个带特定上下文的新的函数。

有两种语法:语法1:$(selector).proxy(function,context)

                      语法2:$(selector).proxy(context,name)

参数:

function要被调用的已有的函数。context函数所在的对象的名称。name已有的函数,其上下文将被改变(应该是 context 对象的属性)。例:

1、$(document).ready(function(){
test=function()
{
this.txt="这是一个对象属性";
$("div").click($.proxy(this.myClick,this));
};

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

var x = new test();
});

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

2、$(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>执行 test 函数</button>
<p></p>


原创粉丝点击