在我的项目中,我正在使用正则表达式解析 JavaScript 代码,尤其是像 document.createElement
这样的动态函数。但有人建议我包装 document.createElement
来制作钩子(Hook)。我不明白该怎么做
他们还提供了一个例子:
var f = document.createElement;
document.createElement = function(tagName){
console.log(tagName);
f.apply(document, arguments);
}
此代码正在跟踪 document.createElement
我无法理解如何在我的代码中使用它,任何人都可以帮助我
最佳答案
该代码将存储对原始 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);
关于javascript - Dom 对象的 Hook 是什么意思,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10070341/