ค้นหาเว็บไซต์

typescript - Type Script หลังจากคอมไพล์จะอ้างอิง this ของขอบเขตระดับโลก


สวัสดีทุกคน ผม/ฉันใหม่ใน TypeScript ผม/ฉันกำลังพยายามเขียนฟังก์ชันบางตัว อ้างอิงถึง this ของฟังก์ชัน และหลังจากคอมไพล์ ผม/ฉันได้รับ this ของ Window ผม/ฉันไม่เข้าใจว่าทำไมมันถึงเป็นแบบนี้ ขอบคุณสำหรับคำแนะนำใด ๆ นี่คือโค้ด

TS

var checkSection  = () => {
$('.section').each((index)=> {
        var $this     = $(this),
            topEdge:number   = $this.offset().top,
            bottomEdge:number = topEdge + $this.height(),
            wScroll:number   = $(window).scrollTop();

        if(topEdge < wScroll && bottomEdge > wScroll) {
            var current:string = $this.data('section');
            console.log('current data attribute ' + current);
            console.log('current index ' + index);
        }
    })
}

ผลลัพธ์ JS

var _this = this;
var checkSection = function () {
    $('.section').each(function (index) {
        var $this = $(_this), 
            topEdge = $this.offset().top, 
            bottomEdge = topEdge + $this.height(),
            wScroll = $(window).scrollTop();

        if (topEdge < wScroll && bottomEdge > wScroll) {
            var current = $this.data('section');
            console.log('current data attribute ' + current);
            console.log('current index ' + index);
        }
    });
};

คำตอบ #1

นั่นคือสิ่งที่ตัวดำเนินการลูกศรใช้ - เพื่อรักษาบริบทของ this ให้เหมือนกับบริบทที่ฟังก์ชันถูกประกาศ หากคุณไม่ต้องการพฤติกรรมแบบนั้น อย่าใช้ => ใช้ function แทน

อีกทางหนึ่ง อย่าสมมติว่า this ภายใน callback ของ jQuery เป็นการอ้างอิงถึงองค์ประกอบปัจจุบัน แทนที่จะใช้ตัวจัดการไปยังองค์ประกอบที่ถูกส่งเข้าไปใน callback ของ .each ของคุณ:

$('.section').each(function (index, element) {
  var $this = $(element)