JavaScript会覆盖对象方法,但保持原始行为不变

时间:2014-07-18 20:56:45

标签: javascript dom override

我想覆盖对象的一个​​功能,使其当前功能保持不变。请参阅以下示例:

假设我们想在开发人员使用document.write时记录文本:

document.write  = function (text) {
    console.log("You have written ["+ text + "] to document");
    //Now call actual document.write
    document.write(text);
}

//Lets use the above function
document.write("America");

在上面的代码中,必须将“America”一词写入文档以及控制台。 有可能吗?如何做到这一点?

1 个答案:

答案 0 :(得分:2)

首先缓存函数:

var write = document.write.bind(document)

document.write = function (text) {
  console.log("You have written ["+ text + "] to document");
  //Now call actual document.write
  write(text);
}

//Lets use the above function
document.write("America");

替换原生函数不是很好的做法,我建议反对它,特别是document.write,请看这里Why is document.write considered a "bad practice"?

相关问题