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)//这两者是等价的
为函数绑定上下文并返回函数是函数式编程的基础.
- Dojo 扩展 javascript 核心库 - dojo.hitch
- Dojo 扩展 javascript 核心库 - dojo.hitch
- Dojo 扩展 javascript 核心库 - dojo.hitch
- javascript中的闭包以及dojo中的dojo.hitch()
- Dojo 扩展 javascript 核心库 - 数组方法(Array)
- Javascript的回调,闭包与dojo.hitch
- Dojo 学习笔记 之 Dojo hitch&partial
- dojo.hitch与dojo.partial解析
- dojo中lang.hitch()用法
- Dojo 扩展 javascript 核心库 - 组合, 结构化与复制对象
- dojo之理解dojo.hitch及数组方法
- dojo中lang.hitch()的简单用法
- 玩转Javascript函数上下文绑定——Dojo hitch/partial详解
- Javascript图表库: Dojo Charting
- dojo
- dojo
- Dojo
- dojo
- 网络资源链接收集整理
- 采用什么开发工具和GUI组件开发JavaSE应用程序?
- 奋斗黑马程序员----Java之StringBuffer与StringBuilder
- 4.9
- 利用条件运算符的嵌套来完成此题:学习成绩> =90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
- Dojo 扩展 javascript 核心库 - dojo.hitch
- 第五堂课后作业
- 1
- 将NetBeans的快捷键变成Eclipse的?
- 2013编程之美-测试赛
- mysql 安装
- 基于开源工具的测试平台搭建
- TCP/IP SOCKET HTTP及HTTPS之间的关系及各自特性之总结
- 奋斗黑马程序员----Java集合框架之List