Dojo 扩展 javascript 核心库 - dojo.hitch

来源:互联网 发布:java多线程处理高并发 编辑:程序博客网 时间:2024/04/29 21:37

dojo.hitch 是在 Dojo 中直接或间接被广泛使用的函数.

hitch 的中文意思是: 钩住,拴住. 在 Dojo 中, dojo.hitch() 的作用是给一个方法绑定其执行上下文.


在 Dojo 中, dojo.hitch 函数非常重要. 原因有两点: 

1. Javascript 中, 函数不与定义它们的上下文即作用域绑定

2. 在 Dojo 中, 很多函数都用 hitch 的参数传递方式: 第一个参数是上下文对象, 第二个参数是一个函数


例 (函数不与定义它们的上下文即作用域绑定) :

var Student = {college: "MIT",getCollege: function() {return this.college;}}function printCollege(foo) {alert("College: " + foo());}printCollege(Student.getCollege); // "College: undefined", 即 this 的值为 GLOBAL</span>

正确的方法:

printCollege(function() {return Student.getCollege();}); // "College: MIT", this 的值被显示的指定为 Student</span>

函数上下文中 this 的确定规则如下:
函数上下文中this的值是函数调用者提供并且由当前调用表达式的形式而定的。 如果在调用括号()的左边,有引用类型的值,
那么this的值就会设置为该引用类型值的base对象。 所有其他情况下(非引用类型),this的值总是null。然而,由于null对

于this来说没有任何意义,因此会隐式转换为全局对象。


用 dojo.hitch 再次改写上面的正确方法(有两种方式, 如下), 代码看上去简洁清晰了一些:

printCollege(dojo.hitch(Student, Student.getCollege));// hitch 返回 function() {return Student.getCollege.apply(Student, arguments);}printCollege(dojo.hitch(Student, "getCollege"));// hitch 返回 function() {return getCollege.apply(Student, arguments);}

当 dojo.hitch 的第一个参数省略的时候, 相当于把第一个参数设置为 null , 这时 this 的值指的是 global 全局上下文.

当 dojo.hitch 有3个及以上参数的时候, 第三个开始往后的参数被用做 dojo.hitch 返回的匿名函数的参数传入

function printsth(x, y, z) {alert(x + y + z);}var printArg = dojo.hitch(null, "printsth", "我是参数1", "我是参数2");// 返回 function() {return printsth.apply(//null, ["我是参数1", "我是参数2"].concat(arguments))}printArg("这里的参数");//相当于: printsth("我是参数1", "我是参数2", "这里的参数");
如果 dojo.hitch 的第一个参数 上下文 指定为 null, dojo 还提供了另外一个函数:

dojo.hitch(null, handler, args)dojo.partial(handler, args)//这两者是等价的

为函数绑定上下文并返回函数是函数式编程的基础.

原创粉丝点击