如何记录对 JavaScript 对象的成员函数的每次调用?

How to log every call to member functions of a JavaScript object?

我想避免在 JavaScript class 的每个方法中插入 console.log() 语句,但我想知道哪些成员被调用,哪些不被 运行 代码和捕获调试输出。

有没有我可以使用的任何类型的挂钩或处理程序,或者调试库,所以我可以只修改 class 或一个地方的实例,然后通过控制台(或类似)?

class 有很多成员,所以这对我来说会节省时间!以及使我能够更轻松地打开和关闭日志记录。

我的第一个问题..谢谢:)

您可以包装实例上的所有函数。例如,假设 obj 是您要观看的对象:

function wrapObjectFunctions(obj, before, after) {
  var key, value;

  for (key in obj) {
    value = obj[key];
    if (typeof value === "function") {
      wrapFunction(obj, key, value);
    }
  }

  function wrapFunction(obj, fname, f) {
    obj[fname] = function() {
      var rv;
      if (before) {
        before(fname, this, arguments);
      }
      rv = f.apply(this, arguments); // Calls the original
      if (after) {
        after(fname, this, arguments, rv);
      }
      console.log( /*...*/ );
      return rv;
    };
  }
}

(上面的arguments,如果你不熟悉的话,是JavaScript提供的一个神奇的伪数组,它包含调用函数的参数。我知道它看起来像伪代码,但它不是。)

实例:

function Thing(name) {
    this.name = name;
}
Thing.prototype.sayName = function () {
    console.log("My name is " + this.name);
};

var t = new Thing("Fred");
console.log("Before wrapping:");
t.sayName(); // My name is Fred, with no extra logging

console.log("----");

wrapObjectFunctions(
    t,
    function(fname) {
        console.log("LOG: before calling " + fname);
    },
    function(fname) {
        console.log("LOG: after calling " + fname);
    }
);

console.log("After wrapping:");
t.sayName(); // My name is Fred, with no extra logging

function wrapObjectFunctions(obj, before, after) {
    var key, value;

    for (key in obj) {
        value = obj[key];
        if (typeof value === "function") {
            wrapFunction(obj, key, value);
        }
    }

    function wrapFunction(obj, fname, f) {
        obj[fname] = function() {
            var rv;
            if (before) {
                before(fname, this, arguments);
            }
            rv = f.apply(this, arguments); // Calls the original
            if (after) {
                after(fname, this, arguments, rv);
            }
            console.log(/*...*/);
            return rv;
        };
    }
}