عند استدعاء وظيفة JavaScript، كيف يمكنني تعيين قيمة مخصصة من "هذا"؟

StackOverflow https://stackoverflow.com/questions/915587

سؤال

أنا أستخدم jQuery ولدي وظيفة تعمل كعناصر رد على الحدث، وهكذا في هذه الوظيفة "هذا" يمثل الكائن الذي تم التقاط الحدث. ومع ذلك، هناك مثيل حيث أريد أن أسمي الوظيفة صراحة من وظيفة أخرى - كيف يمكنني تعيين ما "هذا" يساوي داخل الوظيفة في هذه الحالة؟

علي سبيل المثال:

function handleEvent(event) {
    $(this).removeClass("sad").addClass("happy");
}

$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked

function differentEvent(event) {
    $("input.sad").keydown(e) {
        doSomeOtherProcessing();
        handleEvent(e); // in this case, "this" will be the window object
                        // but I'd like to set it to be, say, the input in question
    }
}
هل كانت مفيدة؟

المحلول

يستخدم تطبيق يتصل.

handleEvent.call(this, e);

نصائح أخرى

مجرد معلمات الوظيفة التي تهتم بها:

function doStuff(el) {
    $(el).removeClass("sad").addClass("happy");
}

function handleEvent(event) {
    doStuff(this);
}

$("a.sad").click(handleEvent); // in this case, "this" is the anchor clicked

function differentEvent(event) {
    $("input.sad").keydown(e) {
        doSomeOtherProcessing();
        doStuff(this);
    }
}

يستخدم

e.target

أود تقديم المشورة لك إعادة تعيين وظيفتك كجدارة مسج.

ولكن هنا إصلاح سريع:

handleEvent.apply(this,e) //transfers this from one scope, to another

إذا كنت تبحث ببساطة الاتصال بمعالج أحداث واحد كما لو كان يتم تشغيله بشكل طبيعي، apply/call سوف تعمل بشكل جيد. ومع ذلك، اعتمادا على احتياجاتك، قد يكون الأمر أكثر قوة لاستخدام إصدار الوسيطة الصفر من jQuery's انقر() وظيفة، والتي سوف تؤدي الكل انقر فوق معالجات هذا العنصر:

function differentEvent(event) {
    $("input.sad").keydown(e) {
        doSomeOtherProcessing();
        $(this).click(); // simulate a click
    }
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top