简体   繁体   English

如何从内部访问函数对象?

[英]How to access a function object from within?

Suppose I want to register a single-use event listener on a button, I could write: 假设我想在按钮上注册一次性事件监听器,我可以写:

var someButton;
var once = function() {
  console.log("clicked");
  someButton.removeEventListener("click", once);
};
someButton.addEventListener("click", once);

What if I don't even want to give that function a name? 如果我甚至不想给这个函数命名怎么办? Like: 喜欢:

var someButton;
someButton.addEventListener("click", function() {
  console.log("clicked");
  someButton.removeEventListener("click", /* what goes here? */);
});

You need to give it a name. 你需要给它一个名字。 You can use a named function expression though. 您可以使用命名函数表达式。

someButton.addEventListener("click", function foo () {
  console.log("clicked");
  someButton.removeEventListener("click", foo);
});

It will be scoped so it is only accessible from within the function. 它将作为范围,因此只能从函数内访问它。


Alternatively, use the new (very new, requires Chrome 55 or Firefox 50, no MSIE, Opera or stable Safari support at the time of writing) options syntax for addEventListener: 或者,在addEventListener中使用新的(非常新的,需要Chrome 55或Firefox 50,无需MSIE,Opera或编写本文时的稳定Safari支持)选项语法:

someButton.addEventListener("click", function () {
  console.log("clicked");
}, { once: true });

What if I don't even want to give that function a name? 如果我甚至不想给这个函数命名怎么办? Like: 喜欢:

Just give it a name anyway! 无论如何,只要给它一个名字!

var someButton;
someButton.addEventListener("click", function once() {
  console.log("clicked");
  someButton.removeEventListener("click", once);
});

This has the added bonus that your stack trace will now show the function name. 这有额外的好处,你的堆栈跟踪现在将显示功能名称。

You can give the function a name that isn't in scope anywhere except inside it: 您可以为函数指定一个名称,该名称除了在其中之外的任何位置:

var someButton;
someButton.addEventListener("click", function handler() {
  console.log("clicked");
  someButton.removeEventListener("click", handler);
});

That doesn't create a handler identifier binding in the scope where someButton is. 不会someButton所在的范围内创建handler标识符绑定。 (Historical note: IE8 and earlier had a bug where it did.) (历史记录:IE8和之前的版本有一个错误。)

If you really don't want to do that, and you don't mind using loose mode and using things that are deprecated, you could use arguments.callee instead: 如果你真的不想这样做,并且你不介意使用松散模式并使用已弃用的东西,你可以使用arguments.callee代替:

// NOT RECOMMENDED AT ALL. WILL NOT WORK IN STRICT MODE.
var someButton;
someButton.addEventListener("click", function() {
  console.log("clicked");
  someButton.removeEventListener("click", arguments.callee);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM