jQuery $.proxy() 方法
实例
在 objPerson 内部强制执行 "test" 函数的上下文:
<!DOCTYPE html><html><head><script src="https://libs.baidu.com/jquery/2.1.4/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"));});</script></head><body><button>运行 test 函数</button><p></body></html>
定义与用法
$.proxy 方法接受一个现有函数并返回一个具有特定上下文的新函数。
此方法通常用于将事件附加到上下文指向另一个对象的元素。
提示:如果您绑定从
$.proxy 返回的函数。如果传递了原始函数,jQuery 仍可以解除绑定正确的函数。语法 1
$(selector).proxy(function,context)
语法 2
$(selector).proxy(context,name)
| 参数 | 描述 |
|---|---|
| function | 要调用的现有函数 |
| context | 函数所在对象的名称 |
| name | 将更改其上下文的现有函数(应该是上下文对象的属性) |