Monday, January 21, 2008

keywords of this in javascript methods

<html>
<head>
<title> cloures </title>
<script src="/lib/prototype/prototype.js" type="text/javascript"></script>

<script type="text/javascript">
var o = {};
var obj = {
name: 'A nice demo in obj',
fx: function() {
return this.name + " " + $A(arguments).join(', ');
},
rf: function() {
return function() { return this.name + " " + $A(arguments).join(', '); }
}
};
alert(obj.fx);
window.name = 'I am such a beautiful window!';
function runFx(f) {
return f();
}
var fx2 = obj.fx.bind(obj, 'otherArg1', 'otherArg2');
var rf2 = obj.rf.bind(obj, 'otherArg1', 'otherArg2');
alert(fx2);
document.write(runFx(obj.fx));
document.write("<br />");
document.write(runFx(fx2));
document.write("<br />");
document.write(obj.rf()());
document.write("<br />");
document.write(rf2()());
document.write("<br />");
</script>
</head>
<body>
Javascript的闭包函数(如将函数做为另一个函数/方法的参数或者是返回结果为函数)中的this会因为闭包函数使用环境不同而变化。
<br />
prototype.js里加了一个bind方法可以把this重新绑回到原对象上(如fx方法所示),但如果返回的是闭包函数,则其中的this会指向新的object(如rf2方法所示指向了window)
</body>
</html>

No comments :