对于长篇大论的标题感到抱歉,但我认为它总结了我的问题
我已经创建了一个jsfiddle来减少并创建一个我的困境的简化问题 http://jsfiddle.net/afw6k/3/
<input id="txtA"/>
<!-- after setupOnclick is executed my onlick for txtA should be onclick="someObj.log("Clicked!")"-->
<script>
function someObject(field){
this.field = field;
this.log = function(msg){
if(this.field.value != "") this.field.value += ", ";
this.field.value += msg
}
this.setupOnlick = function(){
field.onlick = function(){//So how do I pass this (as in someObject) to this?
this.log("Clicked!"); //As if I have written someObj.log("Clicked!");
}
}
}
var someObj = new someObject(document.getElementById("txtA"));
someObj.setupOnlick();
</script>
我不是在点击时只是简单地在文本框中写东西,但上面是我想在这里完成的简化版本。
将此(对象)传递给对象函数嵌套函数
或者有更好的方法来实现这个目标吗?
答案 0 :(得分:4)
将this
保存在变量中:
this.setupOnlick = function(){
var theObj = this;
field.onlick = function(){//So how do I pass this (as in someObject) to this?
theObj.log("Clicked!"); //As if I have written someObj.log("Clicked!");
}
}
this
的值只是一个值,因此可以将其复制到另一个变量中。变量“theObj”在运行时将保留在“click”处理程序的范围内。