Javascript中匿名函数中调用函数时如何使用"this"关键字?

How to use the "this" keyword when calling a function in an anonymous function in Javascript?

我想调用一个原本只是匿名函数的函数,但结果我的代码中需要这个函数 3 次。 所以我定义了一个这样的函数:

function saveButton() {
  this.parentElement.parentElement.querySelector('h3').innerHTML = this.parentElement.querySelector('input[name="task-title"]').value;
  this.parentElement.parentElement.querySelector('p').innerHTML = this.parentElement.querySelector('textarea').value;
  this.parentElement.parentElement.querySelector('.popup').className = 'popup hidden';
  this.parentElement.parentElement.querySelector('.overlay').className = 'overlay hidden';
  saveWork();
};

我想像这样在匿名函数中调用这个函数:

confirmButton.onclick = function()
    saveButton();
};

但是后来我发现我不能在匿名函数中使用this。如何在匿名函数中调用confirmButton()

confirmButton.onclick = saveButton;

confirmButton.onclick = function(){
    saveButton.call(this);
};

尽管 DOM 节点和您要调用的函数同名不是一个好习惯。将您的函数重命名为更有意义的名称,例如 buttonClick

通过查看您发布的代码 fragment,并猜测一些事情,我建议进行以下重构:

function saveButton(parentElem) {
  var myParent = parentElem || this.parentElement;
  myParent.parentElement.querySelector('h3').innerHTML = myParent.querySelector('input[name="task-title"]').value;
  myParent.parentElement.querySelector('p').innerHTML = myParent.querySelector('textarea').value;
  myParent.parentElement.querySelector('.popup').className = 'popup hidden';
  myParent.parentElement.querySelector('.overlay').className = 'overlay hidden';
  saveWork();
}

confirmButton.onclick = function() {
  // I suppose when this function is called somewhere else,
  // you actually know who is the parent element, so:
  saveButton(document.querySelector('.theParentElement'));
};

// If you calling it somewhere where "this" is available,
// then simply call the function with no arguments:
saveButton();

也许上述示例的一些变体可以帮助您。除此之外,如果不查看您的大部分代码,我想不出更好的答案。

您尝试过使用函数表达式吗? 本质上它意味着将函数分配给变量。 阅读 this 答案以了解函数表达式和函数声明之间的区别。

关于你的问题,大部分情况是这样的:

您想使用给定匿名函数的父作用域。

如果是这样,我会推荐这个巧妙的小技巧:

var self = this;

this.saveButton = function() { // or self.saveButton...
  this.parentElement.parentElement.querySelector('h3').innerHTML = this.parentElement.querySelector('input[name="task-title"]').value;
  this.parentElement.parentElement.querySelector('p').innerHTML = this.parentElement.querySelector('textarea').value;
  this.parentElement.parentElement.querySelector('.popup').className = 'popup hidden';
  this.parentElement.parentElement.querySelector('.overlay').className = 'overlay hidden';
  saveWork();
};

confirmButton.onclick = function() {
    self.saveButton();
}

此技巧可用于任何级别的范围深度,只是不要污染全局命名空间:)