正确的传递方式'this'在javascript中运行

Correct way to pass 'this' to function in javascript

本文关键字:javascript 运行 this 方式      更新时间:2023-09-26

我的javascript是相当基本的,所以我想我会问专家是否我目前的方法是正确的,如果有更好的,更接受的方法。

通常我会使用jquery的。on事件来触发一个函数,像这样:

$("body").on("input", "textarea", textareaAutoGrow);
function textareaAutoGrow() {
    var pad = $(this).outerHeight(false) - $(this).innerHeight();
    this.style.height = "auto";
    this.style.height = (this.scrollHeight + pad) + "px";
}

这样,' This '是自动传递的,但是我现在需要对所有文本区域的窗口大小调整事件做同样的事情,而不仅仅是一个特定的。

我是这样做的:

$(window).on("resize", refreshAutoGrow);
function refreshAutoGrow() {
        $el = $(".text-field.autogrow").filter(function () {
            return $(this).val();
        });
        $el.each(function () {
            textareaAutoGrow.call(this);
        });
    }

我已经使用。call调用了textareaAutoGrow函数——这是我从jquery小部件中学习到的。

它工作,但正如我说的,这是一个很大的猜测-这是正确的方法,或者有更接受的方式做我想要的?

each设置为resize时触发,以循环文本区域:

function textareaAutoGrow() {
    var pad = $(this).outerHeight(false) - $(this).innerHeight();
    this.style.height = "auto";
    this.style.height = (this.scrollHeight + pad) + "px";
}
$("body").on("input", "textarea", textareaAutoGrow);
$(window).on("resize", funtion() {
    $("textarea").each(textareaAutoGrow);
});