每次执行函数时,Javascript ES5 : How to extend the Function object in order to set a property value on itself,?

标签 javascript extending-classes

我目前有以下工作代码:

Function.prototype.GetLastCallerName = function () {
  if (!this.arguments || !this.arguments.callee || !this.arguments.callee.caller) return null;
  var result = /^function\s+([\w\$]+)\s*\(/.exec(this.arguments.callee.caller.toString());
  this.LastCaller = result ? result[1] : 'Anonymous';
  return this.LastCaller;
};

我从另一个线程中获取了该代码。如您所见,它扩展了 Function.prototype 以添加一个名为 GetLastCallerName 的方法,该方法选择最后调用的函数名称并 (1) 将其设置为 LastCaller Function.LastCaller 并 (2) 返回它。

为了让它工作:

function MyFunction1() {
  MyFunction1.GetLastCallerName();
  console.log(MyFunction.LastCaller);
}

function MyFunction2() { 
  MyFunction1(); 
}

MyFunction2();

我希望能够做的事情:消除每次都使用 GetLastCallerName() 并按顺序扩展 Function 的需要每次调用任何函数时执行该获取。

最佳答案

到目前为止,我一直在努力遵循您的示例所做的尝试,但我想我明白您想做什么。为什么不利用 classes , 和 extend在他们身上为您的用例。查看以下示例...

class Base {

  baseFn() {
    console.log('from base');
  }
}

class Thing extends Base {

  fn1() {
    this.baseFn();
  }
}

let thingee = new Thing();

thingee.fn1();

所以 baseFn 现在总是在调用 fn1 时被调用。

JSFiddle Link - class demo


在您的一些评论中,您似乎想要获得“最后调用函数的名称”。将调用者本身的实例传回父级怎么样?这肯定会给你更大的灵 active ,因为现在你可以随心所欲地塑造你的来电者。查看以下...

class Base {

  baseFn(caller) {
    console.log(caller.id); // 1
  }
}

class Thing extends Base {

  constructor(id) {
    super();

    this.id = id;
  }

  fn1() {
    this.baseFn(this);
  }
}

let thingee = new Thing('1');

thingee.fn1();

现在您可以将您想要的任何内容添加到您的 Thing 实例中,在本例中,添加一个 id1 的对象当 fn1 传播到 baseFn

时可以检查

JSFiddle Link - caller demo

关于每次执行函数时,Javascript ES5 : How to extend the Function object in order to set a property value on itself,?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47266361/

相关文章:

c# - 有没有办法异步过滤 IList?

javascript - $ 在 Angular 中未定义或 document.getElementById() 为 Null

javascript - 什么正则表达式会匹配从 0.5 到 24 的这个值

c# - 为什么仅在实现接口(interface)后才重写方法?

ios - 将 UIViewController 实现拆分为多个源文件

javascript - 使用 PHP 导出为带有中文字符的 CSV

javascript - 使用javascript更改标签颜色的问题

PHP 子类不能实现相同的接口(interface)父类实现

asp.net - ASP.NET C# 中的自定义控件

c# - 扩展TextBox控件并更改部分默认样式