检索正确的“;这个“;在javascript中

retrieving the correct "this" in javascript

本文关键字:javascript 这个 检索      更新时间:2023-09-26

我已经构建了自己的对象:

Main.utilities.pool = function (pool) {
    var counter=0;
    var $form = $(pool);
    return {
        add_pool_field: function(){
            $form.find('#practice_type').change(function() {
                if($(this).find("option:selected").val()){
                    var time = new Date().getTime();
                    var regexp = new RegExp( $(this).find("option:selected").data('id'), 'g');
                    $("#items").append('<li class="colorize">' + '<h1>' + this.increment_counter() + '</h1>' + $(this).find("option:selected").data('fields').replace(regexp, time) + '</li>');
                }
            });
        },
        increment_counter: function(){
            return ++counter;
        },
        init: function() {
            this.add_pool_field();
        }
    }
}

我这样称呼它:

var $profile_pool = Main.utilities.pool($('#new_form')).init();

问题出在更改事件中,这指的是一个选择字段。但是,我想访问从pool函数返回的实际任意对象的increment_counter函数。当我尝试this.increment_counter()时,它认为这是html选择字段,所以它爆炸了。如何在传递给更改的函数的上下文中访问该对象?

只需在add_pool_field()的本地作用域中保存对this的引用。

    add_pool_field: function(){
        var self = this;
        $form.find('#practice_type').change(function() {
            if($(this).find("option:selected").val()){
                var time = new Date().getTime();
                var regexp = new RegExp( $(this).find("option:selected").data('id'), 'g');
                $("#items").append('<li class="colorize">' + '<h1>' + self.increment_counter() + '</h1>' + $(this).find("option:selected").data('fields').replace(regexp, time) + '</li>');
            }
        });
    },

您需要保留对所需this的引用,通过其他变量-将其声明为变量

var t = this;

然后在change函数中,使用t访问对象的this