Wednesday, May 07, 2008

test scope of this in closure and in anonymous functions

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title>test scope of this in closure and in anonymous functions</title>
<script type="text/javascript">
var foo = 'this is window.foo!';
var d = [1, 2, 3];
// timeout functions
function Constructor() {
this.foo = 'this is Constructor.foo!';
var that = this;
this.timerId = window.setTimeout(function() {
// alert(this); // will get [object Window]
alert("this.foo = " + this.foo);
alert("that.foo = " + that.foo);
} , 1000);
}
// local functions
Constructor.prototype.getFoo = function() {
alert(this); // [object Object]
var getExternalFoo = (function() {
// alert(this); // will get [object Window]
return d.concat(this.foo)
})();
return getExternalFoo;
};
// using Function.call(object)
Constructor.prototype.getBar = function() {
var getInternalFoo = (function() {
// alert(this); // will get [object Object]
return d.concat(this.foo)
}).call(this);
return getInternalFoo;
};
var f = new Constructor();
document.write(f.getFoo());
document.write("<br />");
document.write(f.getBar());

</script>
</head>
<body>
</body>
</html>

在window.setTimeout和全局环境中的匿名方法中的this是指向window对象的,所以在调用过程中可以将此匿名方法做为实际的某个对象(如this对象)的方法来调用.

No comments :