javascript - ES6 - 如何在绑定(bind) `this` 类后访问 `this` 元素?

标签 javascript jquery ecmascript-6 this

如何访问 this绑定(bind)后的元素 this类(class)?

例如不绑定(bind)this :

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

有绑定(bind)this :

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

如何获取和访问 <a href="#" class="button-open">Open</a>绑定(bind)后再次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}

有什么想法吗?

编辑:

jQuery 同样的问题 animate :

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

绑定(bind)后:

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

获取 element 的任何全局或防弹方式又是?

最佳答案

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

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

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

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

由于您使用 ES6 标记了问题,因此最好将上下文与 arrow function 绑定(bind)因为使用 bind更冗长,还创建了一个附加功能:

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

3. 另一种选择是使用 target事件对象的属性,但这也可以是元素中的任何子元素(目标是调度事件的元素,而不是绑定(bind)处理程序的元素),因此可能需要遍历 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
});

关于javascript - ES6 - 如何在绑定(bind) `this` 类后访问 `this` 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40815670/

相关文章:

javascript - 检查鼠标输入的元素内容

javascript - 隐藏右框阴影以制作垂直制表符

javascript - 在没有 Jquery 的情况下单击将类添加到子元素

jquery - 如何向 Phoenix 项目添加 CSS/JS 依赖?

javascript - 为相同的属性添加对象和数组

javascript - 使用 CharCodeAt 与索引而不是句子

JavaScript 在 Internet Explorer 中不工作

javascript - 防止图像在 AngularJs 中渲染

javascript - 渐进增强和初始显示状态

javascript - 将一个js文件包含到另一个在文档中编写的js文件中