1

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

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

我不是想在单击时简单地向文本框写一些东西,但上面是我在这里尝试完成的简化版本。

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

还是有更好的方法来实现这一点?

4

1 回答 1

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

于 2012-07-24T12:56:47.193 回答