gpt4 book ai didi

javascript - 将此(对象)传递到对象方法之一嵌套方法

转载 作者:行者123 更新时间:2023-11-30 10:39:55 24 4
gpt4 key购买 nike

抱歉标题冗长,但我认为它总结了我的问题

我创建了一个 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>

我并不是想在单击时简单地向文本框写入内容,但上面是我在这里尝试完成的内容的简化版本。

将 this(对象)传递给对象函数嵌套函数

或者是否有更好的方法来实现这一点?

最佳答案

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”处理程序的范围内。

关于javascript - 将此(对象)传递到对象方法之一嵌套方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11631313/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com