Click here to Skip to main content
15,891,828 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
JavaScript
onload=function(){  
	 var o={
		name:"the o_object",
		 oo:{
			name:"zhuzhu",
			f1:function(){
				return function (){
					 return this.name;
				}
			}
		} 
	 };  
	 alert(o.oo.f1()());    
}
Posted
Updated 4-Oct-14 8:54am
v2
Comments
Sergey Alexandrovich Kryukov 4-Oct-14 15:30pm    
Why doing such pointless tricks?
If f1 returned not the function but this.name, it would work.
—SA

1 solution

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:
JavaScript
o = {
   name: "the o_object", // irrelevant to the problem
   oo: {
      name: "zhuzhu",
      f1: function() {
         return this.name;
      }
   } 
}; 
alert(o.oo.f1()); //will show "zhuzhu"


[EDIT #1]

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:
C#
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"
[EDIT #2]

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
 
Share this answer
 
v4

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900