JavaScript猴子修补

时间:2016-06-29 11:52:52

标签: javascript

我从JS书中获取此代码。我没有得到什么样的方法我作为参数(m)传递给这个函数。当我这样做时,它输出undefined:

function trace(o, m) {
  var original = o[m]; // Remember original method in the closure.

  o[m] = function() { // Now define the new method.
    console.log(new Date(), "Entering:", m); // Log message.
    var result = original.apply(this, arguments); // Invoke original.
    console.log(new Date(), "Exiting:", m); // Log message.
    return result; // Return result.
  };
}

var a = {
  x: 1,
  y: 2
};

var plus = function(obj) {
  return this.x + this.y;
}

2 个答案:

答案 0 :(得分:2)

o是对象,m是方法名称

/**
 * Modifies a given object's property by making it log
 * the enter/exit times of a method call
 * @param {object} o object that has a method that will be called
 * @param {string} m name of the method within the given object
 */
function trace(o, m) {
    var original = o[m]; // Remember original method in the closure.

    o[m] = function() { // Now define the new method.
        console.log(new Date(), "Entering:", m); // Log message.
        var result = original.apply(this, arguments); // Invoke original.
        console.log(new Date(), "Exiting:", m); // Log message.
        return result; // Return result.
    };
}

var obj = {
  doSomething: function() {
      console.log('obj.doSomething was called');
  }
};

// Won't log enter/exit times
obj.doSomething();
trace(obj, "doSomething");
// Will log enter/exit times
obj.doSomething();

答案 1 :(得分:0)

这是一个例子。

参数o必须是一个对象。第二个参数m是o中方法的名称。 trace方法替换了对象中的方法。新方法添加了一些日志记录并调用替换的方法。



function trace(o, m) {
    var original = o[m]; // Remember original method in the closure.

    o[m] = function() { // Now define the new method.
        console.log(new Date(), "Entering:", m); // Log message.
        var result = original.apply(this, arguments); // Invoke original.
        console.log(new Date(), "Exiting:", m); // Log message.
        return result; // Return result.
    };
}

var a = {x:1, y:2};

var plus = function (obj) {
    return this.x + this.y;
}
var test = {
	method : plus
}
trace(test, "method");
test.method(a);