<script type="text/javascript">
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
}; } }; alert(object.getNameFunc()());
</script>
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
}; } }; alert(object.getNameFunc()());
</script>
像这道题要是让你解决怎么能弹出name值,就这样写~·window.onload = function(){
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
that = this;
return function(){
return that.name;
}; } }; alert(object.getNameFunc()()); };
弹出的name 值为My Object
因为咱们用了一个that = this;来引用当前对象object,所以它弹出来的是object对象的name值
...
getNameFunc : function(){
return function(){
return this.name;
}; }
...如果翻译成这样:
...
this.getNameFunc = function(){
var tmp = function(){
return this.name;
}
return tmp();
}
...
可以这样翻译吧 我不是很肯定 我觉得这样当取this.name的时候 this应该已经不是object对象了
楼主你发的代码我用FF,IE都弹不出来你说的这个"The Window"值
我弹出来的都是空值,我不知道你用的是什么先进的浏览器。你可以自己试试~··
window.onload = function(){
};这里试试~···
<script type="text/javascript">
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : (function(n){
return function(){return n;}
})(this.name)
}; alert(object.getNameFunc());
</script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>学习JavaScript闭包</title>
<script type="text/javascript">
var name = "The Window";
var object = {
name : "My Object",
getNameFunc : function(){
return function(){
return this.name;
}; } };
alert(object.getNameFunc()()); </script>
</head><body>
</body>
</html>
var name = "The Window";
alert(this===window?"this===window":"this===object");
var object = {
name : "My Object",
getNameFunc : function(){
alert(this===window?"this===window":"this===object");
return function(){
alert(this===window?"this===window":"this===object");
return this.name;
}; } };
alert(object.getNameFunc()());
</script>为了避免this回乱变, 推荐的方法是用call来修正它, 看例子:<script type="text/javascript">
var name = "The Window";
alert(this===window?"this===window":"this===object");
var object = {
name : "My Object",
getNameFunc : function(){
alert(this===window?"this===window":"this===object");
//临时函数
var _f = function(){
alert(this===window?"this===window":"this===object");
alert(this.name);
};
return function(){
_f.call(object);//这样的话this就绝对指向你object
//也可以call window
//_f.call(window);//this绝对指向window
} } };
object.getNameFunc()();
</script>