1

在我的项目中,我正在解析 JavaScript 代码,尤其是像document.createElement正则表达式这样的动态函数。但有人建议我把它包document.createElement起来做钩子。我不明白该怎么做

他们还提供了一个例子:

var f = document.createElement; 
document.createElement = function(tagName){ 
    console.log(tagName); 
    f.apply(document, arguments); 
} 

此代码正在跟踪document.createElement

我无法理解如何在我的代码中使用它,任何人都可以帮助我

4

1 回答 1

2

该代码将存储对原始代码的引用document.createElement,然后重新分配document.createElement以指向新函数。

在这个新函数内部,它将记录第一个参数,然后调用原始document.createElement()传递document作为它的this值,并按原样传递其余的arguments

这是我将如何编码...

(function() {
    var documentCreateElement = document.createElement;

    document.createElement = function(tagName) {
        console.log(tagName);
        return documentCreateElement.apply(document, arguments);
    }

})();

如果console.log()可能不可用,您可能需要将该行更改为...

window.console && console.log && console.log(tagName);
于 2012-04-09T07:44:03.633 回答