ES6 - 绑定`this`类后如何访问`this`元素?

lau*_*kok 1 javascript jquery this ecmascript-6

如何this在绑定this类后访问元素?

例如,没有绑定this:

$(".button-open").click(function(event) {
    console.log(this); // <a href="#" class="button-open">Open</a>
    this.openMe();
});
Run Code Online (Sandbox Code Playgroud)

有约束力this:

$(".button-open").click(function(event) {
   console.log(this); // Polygon {windowHeight: 965, scrollNum: 0}
   this.openMe();
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

如何<a href="#" class="button-open">Open</a>在绑定后再次访问和访问this

完整代码:

class Polygon {
    constructor() {
        this.windowHeight = $(window).height();
        this.scrollNum = 0;
    }

    // Simple class instance methods using short-hand method
    // declaration
    init() {
        var clickMe = this.clickMe.bind(this);
        return clickMe();
    }

    clickMe() {
        $(".button-open").click(function(event) {
            console.log(this);
            this.openMe();
        }.bind(this));


        $(".button-close").click(function(event) {
            this.closeMe();
        }.bind(this));
    }

    openMe() {
        console.log(this.scrollNum); // 0
        this.scrollNum = 200;
        console.log(this.scrollNum); // 200
        return false;

    }

    closeMe() {
        console.log(this.scrollNum); // 200
        return false;
    }
}

export { Polygon as default}
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

编辑:

与jQuery相同的问题animate:

$(".element").animate({}, 'fast', 'swing', function(event) {
    console.log(this); // the element
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

绑定后:

$(".element").animate({}, 'fast', 'swing', function(event) {
    console.log(this); // undefined
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

任何全球或防弹的方式element再次获得?

nem*_*035 5

1.最好的选择是将上下文存储在变量中,不要覆盖this:

var context = this;
$('.element').on('click', function(event) {
  // context would be the this you need
  // this is the element you need
});
Run Code Online (Sandbox Code Playgroud)

2.如果您只针对单个元素,则可以从上面执行相反的操作,并将要将处理程序绑定到的变量元素保存到变量中,然后使用处理程序中的变量:

var el = $('.element');
el.on('click', function(event) {
  // use el here
}.bind(this));
Run Code Online (Sandbox Code Playgroud)

由于您使用ES6标记了问题,因此使用箭头函数绑定上下文可能更好,因为使用bind更加冗长并且还创建了一个附加函数:

var el = $('.element');
el.on('click', (event) => {
  // this is the same as in the outer scope
  // use el here
});
Run Code Online (Sandbox Code Playgroud)

3.另一种选择是使用事件对象的target属性,但这也可以是元素中的任何子元素(目标是调度事件的元素,而不是绑定处理程序的元素),因此可能需要遍历DOM树以找到您需要的元素,效率较低.

var el = $('.element');
el.on('click', ({ target }) => {
  while (target.parentNode && !target.classList.contains('element')) {
    target = target.parentNode;
  }
  // here the target should be the element you need
});
Run Code Online (Sandbox Code Playgroud)