如何显示名称="o_object"?现在结果为空,为什么呢? [英] how to display name = "o_object"? Now the result is null why?

查看:119
本文介绍了如何显示名称="o_object"?现在结果为空,为什么呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

onload=function(){  
	 var o={
		name:"the o_object",
		 oo:{
			name:"zhuzhu",
			f1:function(){
				return function (){
					 return this.name;
				}
			}
		} 
	 };  
	 alert(o.oo.f1()());    
}

推荐答案

这是因为this.name在函数f1的上下文中,但不在您从f1返回的函数中,具有不同的"this",即不包含name属性的对象.

例如,比较:
This is because this.name is in the context of the function f1, but not in the function you returned from f1, which has different "this", the object which does not contain name property.

For example, compare:
o = {
   name: "the o_object", // irrelevant to the problem
   oo: {
      name: "zhuzhu",
      f1: function() {
         return this.name;
      }
   } 
}; 
alert(o.oo.f1()); //will show "zhuzhu"





现在,让我们找出f1中return语句中使用的不同"是什么.这是功能对象f1本身.要对其进行检查,请为它提供一个属性以进行标识,然后将此属性称为innerName.然后进行检查将显示该属性的值:





Now, let''s figure out what is that "different this" used in return statement in f1. This is the function object f1 itself. To check it up, let''s give it a property to identify it, and call this property innerName. Then out check-up will show the value of this property:

o = {
   name:"the o_object",  // irrelevant to the problem
      oo: {
         name: "zhuzhu",
         f1: function(){
            innerName = "function itself";
            return function () {
                return this.innerName;
            }
         }
      } 
   };
alert(o.oo.f1()()); // will show "function itself"



顺便说一下,第二种情况展示了 closure 的有趣示例,它是编程中非常重要的概念.请参阅: http://en.wikipedia.org/wiki/Closure [



By the way, the second case presents the interesting example of closure, a very important concept in programming. Please see: http://en.wikipedia.org/wiki/Closure[^].

—SA


这篇关于如何显示名称="o_object"?现在结果为空,为什么呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆