【问题标题】:Javascript stop "this" keyword from change on function call? [duplicate]Javascript阻止“this”关键字更改函数调用? [复制]
【发布时间】:2018-05-04 17:55:44
【问题描述】:

我想知道。我有一个按钮,按下时我会调用一个函数。我使用 JQuery 这样做:

this.chose_button.on('click', function() {
  tryInputSong(this, this.link_input.val());
});

但问题是我需要“tryInputSong”的输入参数与“this.chose_button”中的“this”关键字相同,而不是“this.chose_button”对象本身。有没有办法可以阻止“this”关键字将值更改为 this.chose_button 或者我必须以某种方式通过另一个函数传递我想要的对象?

我真的很困惑如何解决这个问题,我希望能得到一些帮助,谢谢! :)

【问题讨论】:

  • var oldThis = this 然后你可以做tryInputSong(oldThis, oldThis.link_input.val());

标签: javascript onclick this call keyword


【解决方案1】:

JS 引入了箭头函数,让你可以引用外部的this 值。

this.chose_button.on('click', event => 
  tryInputSong(this, this.link_input.val())
);

因为箭头函数不绑定自己的本地this,所以它使用来自外部环境的那个。

我上面展示的语法只有一个表达式作为函数体。如果您需要多个语句,则使用花括号定义主体,就像使用传统的 function 语法一样。

您仍然可以通过event.currentTarget 获取对绑定元素的引用。

【讨论】:

  • 箭头功能的可用性取决于所需的浏览器支持以及是否使用 babel 进行编译。
  • @lkroneman:是的,非常正确。
【解决方案2】:

通常的老派解决方法是从您想要的上下文中存储对此的引用并在以后重用它:

var self = this;
this.chose_button.on('click', function() {
  tryInputSong(self, self.link_input.val());
});

你也可以在你的函数上显式地绑定 this 的值:

this.chose_button.on('click', function() {
  tryInputSong(this, this.link_input.val());
}.bind(this));

或者,如果您的环境支持 ES6 箭头函数(或者您使用转译器添加相应的 polyfill),那么您可以使用 arrow function,它不会更改 this 的绑定

this.chose_button.on('click', () => {
  tryInputSong(this, this.link_input.val());
});

【讨论】:

    【解决方案3】:

    你可以这样做:

    var self = this;
    this.chose_button.on('click', function() {
      tryInputSong(self, self.link_input.val());
    });
    

    或者使用箭头函数:箭头函数没有自己的this;使用了封闭执行上下文的 this 值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 2013-12-17
      • 2019-05-26
      • 1970-01-01
      相关资源
      最近更新 更多