var foo = {
p1: function(){
return this.p2;
},
p2: function(){
console.log('i am foo.p2');
}
};
我正在尝试做与上面的示例类似的事情,但是当我调用时遇到了一个问题:
var result = foo.p1();
结果 == '未定义'
我对“this”在对象上下文中的工作方式感到困惑。有人可以解释我在哪里出错了吗?
编辑 更完整的例子:
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(){}
};