Type= {
Container: $get('ctl00_Main_rbtnlst_Type'),
Local: this.Container.getElementsByTagName('input'),
Foreign:this.Container.getElementsByTagName('input')
}
当我在 firebug 控制台中运行此代码时,我收到错误“this.Container”未定义,即使它已定义。我还能如何访问 Local 和 Foreign 属性中的 Container 属性。我什至试过了。
Type= {
Container: $get('ctl00_Main_rbtnlst_Type'),
Local: Container.getElementsByTagName('input'),
Foreign:Container.getElementsByTagName('input')
}
最佳答案
你不能在实例化时得到this
。你可以这样做:
Type= {
Container: $get('ctl00_Main_rbtnlst_Type'),
Local: function(){return this.Container.getElementsByTagName('input');},
Foreign: function(){return this.Container.getElementsByTagName('input');}
}
然后使用 Type.Local()/Type.Foreign()
或者如果您需要实例中的本地/外部,请使用此冗余模式:
Type= {
Container: $get('ctl00_Main_rbtnlst_Type'),
Local: $get('ctl00_Main_rbtnlst_Type')
.getElementsByTagName('input');},
Foreign: $get('ctl00_Main_rbtnlst_Type')
.getElementsByTagName('input');}
}
或者使用这个立即执行的函数:
var Type = (function(){
var container = $get('ctl00_Main_rbtnlst_Type'),
local = container.getElementsByTagName('input'),
foreign = container.getElementsByTagName('input');
return {
Container: container,
Local: local,
Foreign: foreign
}
})();
为了完整起见,您还可以使用一些 getter
,但这在所有浏览器中都不起作用(尤其是在 IE<9 中)
var Type = {
Container: $get('ctl00_Main_rbtnlst_Type'),
get Local() {return this.Container.getElementsByTagName('input');},
get Foreign() {return this.Container.getElementsByTagName('input');}
}
注意:Local
和Foreign
是一样的,这是你想要的吗?
关于javascript - 'this'在javascript中的对象内部未定义,通过另一个属性访问对象的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6057205/