Dojo 扩展 javascript 核心库 - dojo.hitch

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)
//这两者是等价的

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值