var foo = {
p1: function(){
return this.p2;
},
p2: function(){
console.log('i am foo.p2');
}
};
I’m trying to do something similar to the example above, however I’m running into an issue where when I invoke:
var result = foo.p1();
result == ‘undefined’
I’m confused about the way ‘this’ works within object context. Could someone explain where I’m going wrong here?
EDIT
more complete example:
suite_segments.themis = {
//don't re-run themis initialization script
initialized: false,
/**
* Initializer for themis product. Returns true if initialization
* operations were performed, false if not (most likely because
* the product was already initialized -- not a fresh navigation)
*/
init: function(){
//prevent multiple initializations
if(this.initialized)
return false; //did not initialize
this.initialized = true;
//operations
jQuery('#tabs').tabs();
//init success
return this.themis_destroy;
},
/* ----------------------------------------------------------------------------------
* DESTRUCTORS
* ----------------------------------------------------------------------------------/
/**
* Function to be invoked if user navigates away from 'themis' entirely. Other
* sub-destroy type functions will be invoked if necessary when a user switches
* between parts of themis
*
*/
themis_destroy: function(){
console.log('themis_destructor');
this.initialized = false;
},
/**
* Designed to be overwritten every time a segment of themis is loaded. Will be invoked
* ever time a segment of themis is loaded.
*/
themis_sub_destroy: function(){}
};
Your completed example will work as well. With your code,
suite_segments.themis.init()will return the descructor function (orfalse), notundefined.But you have an other problem: the destructor won’t work. Read this excellent overview about the
thiskeyword and you’ll see:thispoints to the current context, which is call-dependent. When invoked per...themis.init(), the function will be called in the context of thethemisobject – everything is fine. But the function that is returned (suite_segments.themis.destroy) won’t be called on the object, but (I guess) standalone – and has no chance to set theinitializedproperty of the correct object.In your case, I can recommmend the
.bind()method to set the context of the returned function:See also this blog post about “objects with properties that are functions” or the mythof of methods, which covers exactly your title question, and this post about
this.