[JavaScript] When a DOM object calls back a method of an object, the this of the method points to a problem. How to get the instance?

Upload code

The explanation is in the comments

Switch a list through the tab bar:

 class List {
    
    
     constructor(param) {
    
    
         this.prop = param;
     }
     listToggle() {
    
    
         // ... fun

         // 这个方法通过被回调来切换 tab 栏
         // 当该方法被回调时,我需要两个东西
         // 1.调用者 'div.tab-child1' 2.当前 List 实例,通过该实例取到需要的属性

         // 当前 this 指向的是调用者,此时我该如何取到当前 List 实例?
         console.log(this);
     }
 }
 var list = new List();
 // 对 tab 栏委派事件,子项触发时回调 list 的 listToggle 方法
 $('div.tab').on('click', '.child', list.listToggle);

After thinking for a long time, I wrote like this:

class List {
    
    
    constructor(param) {
    
    
        this.prop = param;
    }
    listToggle(target) {
    
    
        // ... fun
        // 用闭包的方式传参
        return function() {
    
    
            console.log(target);
            console.log(this);
        }
    }
}
var list = new List();
$('.btn-1').on('click',function() {
    
    
    // 传参调用方法
    // 取到闭包
    // 调用闭包 bind 方法取到 [改变了 this 指向的函数拷贝]
    // 调用该函数拷贝
    list.listToggle(this).bind(test)();
});

This article mentioned several function methods bind call and apply

https://blog.csdn.net/qq_16181837/article/details/104965043

Found a simpler way of writing, we get the caller through the event object:

class List {
    
    
    constructor(param) {
    
    
        this.prop = param;
    }
    listToggle(jq_e) {
    
    
		// ... fun
        console.log(jq_e.target);
        console.log(this);
    }
}
var list = new List();
$('.btn-1').on('click', list.listToggle.bind(list));

Guess you like

Origin blog.csdn.net/qq_16181837/article/details/104985379