jQuery 中$.proxy 使用
定义和用法
$.proxy 方法接受一个已有的函数,并返回一个带特定上下文的新的函数。
该方法通常用于向上下文指向不同对象的元素添加事件。(说白了就是改变 this 指向,保持特定的上下文 context)
提示:如果您绑定从 $.proxy 返回的函数,jQuery 仍然可以通过传递的原先的函数取消绑定正确的函数
-
jQuery.proxy( function, context )
function:将要改变上下文语境的函数。
context:函数的上下文语境(`this`)会被设置成这个 object 对象。
-
jQuery.proxy( context, name )
context:函数的上下文语境会被设置成这个 object 对象。
name:将要改变上下文语境的函数名(这个函数必须是前一个参数 ‘context’ 对象的属性)
例子:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>proxy使用</title>
<script src="https://cdn.staticfile.org/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")); // 传入 objPerson 作为上下文对象, test 函数是 objPerson 内部的方法 // 执行结果 Name: John Doe; age: 32
});
</script>
</head>
<body>
<button>执行 test 函数</button>
<p></p>
</body>
</html>

浙公网安备 33010602011771号