javascript – 如何从自己的实现中引用一个函数?

前端之家收集整理的这篇文章主要介绍了javascript – 如何从自己的实现中引用一个函数?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在开发一个由许多对象和函数(对象方法)组成的javascript应用程序.我希望能够在应用程序的生命周期中记录许多事件.我的问题是在记录器内部我想知道哪个函数调用了日志条目,所以我可以将这些数据与日志消息一起保存.这意味着每个函数都需要能够以某种方式引用自身,因此我可以将该引用传递给记录器.
我正在使用javascript严格模式,因此不允许在函数内部使用arguments.callee.

这是一个可以运行的非常简化的代码示例.为了简单起见,我只是在这里使用警报而不是我的记录器.

  1. (function(){
  2. "use strict";
  3. window.myObject = {
  4. id : 'myObject',myFunc : function(){
  5. alert(this.id); // myObject
  6. alert(this.myFunc.id); // myFunc - I don't want to do this. I want something generic for all functions under any object
  7. alert('???') // myFunc
  8. alert(arguments.callee.id); // Will throw an error because arguments.callee in not allowed in strict mode
  9. }
  10. }
  11. myObject.myFunc.id = 'myFunc';
  12. myObject.myFunc();
  13. })();

>在第一个警报中 – 这与myObject有关,而与myFunc无关
>在第二个I警报中 – 我通过其名称引用了该函数,我不想这样做,因为我正在寻找一种从其自己的实现中引用函数的通用方法.
>第三个警报 – 为您的想法开放.
>第四个警报 – 如果我没有“使用stict”,它会起作用.我想保持严格的模式,因为它提供了更好的性能,并构成了良好的编码实践.

任何输入将不胜感激.

如果您不熟悉“严格模式”,这是一个很好的读取它的地方:
JavaScript Strict Mode

最佳答案
这是一个非常黑客的方式:

  1. (function(){
  2. "use strict";
  3. window.myObject = {
  4. id: 'myObject',myFunc: function () {
  5. // need this if to circumvent 'use strict' since funcId doesn't exist yet
  6. if (typeof funcId != 'undefined')
  7. alert(funcId);
  8. },myFunc2: function () {
  9. // need this if to circumvent 'use strict' since funcId doesn't exist yet
  10. if (typeof funcId != 'undefined')
  11. alert(funcId);
  12. }
  13. }
  14. // We're going to programatically find the name of each function and 'inject' that name
  15. // as the variable 'funcId' into each function by re-writing that function in a wrapper
  16. for (var i in window.myObject) {
  17. var func = window.myObject[i];
  18. if (typeof func === 'function') {
  19. window.myObject[i] = Function('var funcId = "' + i + '"; return (' + window.myObject[i] + ')()');
  20. }
  21. }
  22. window.myObject.myFunc();
  23. window.myObject.myFunc2();
  24. })();

从本质上讲,我们通过在找到函数名称后重新编译字符串中的每个函数来绕过’use strict’声明.为此,我们在每个函数周围创建一个包装器,声明一个字符串变量’funcId’等于我们的目标函数名称,这样变量现在通过闭包暴露给函数.

呃,不是最好的做事方式,但它有效.
或者,您可以从内部调用非严格函数

  1. (function(){
  2. "use strict";
  3. window.myObject = {
  4. id: 'myObject',myFunc: function () {
  5. alert(getFuncName())
  6. },myFunc2: function () {
  7. alert(getFuncName());
  8. }
  9. }
  10. })();
  11. // non-strict function here
  12. function getFuncName(){
  13. return arguments.callee.caller.id; // Just fyi,IE doesn't have id var I think...so you gotta parse toString or something
  14. }

希望有所帮助.

猜你在找的JavaScript相关文章