【发布时间】:2012-07-04 20:37:24
【问题描述】:
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(){}
};
【问题讨论】:
-
发布您正在尝试的实际代码或创建fiddle
-
foo.p1()确实产生了foo.p2。发布更完整的sn-p。 -
我不知道,伙计,你的 sn-p 实际上在 JSFiddle 中工作。
suite_segments.themis.init();真的返回suite_segments.themis.themis_destroy。一定有别的东西。
标签: javascript object scope this