JavaScript重写对象方法,但保持原始行为不变

JavaScript重写对象方法,但保持原始行为不变,javascript,dom,overriding,Javascript,Dom,Overriding,我希望重写对象的函数,使其当前功能保持不变。请参见以下示例: 假设我们希望在开发人员使用文档时记录文本 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 doc

我希望重写对象的函数,使其当前功能保持不变。请参见以下示例:

假设我们希望在开发人员使用文档时记录文本

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写入文档和控制台可能吗?如何操作?

首先缓存函数:

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
,请参见此处

我无法理解第一行,它可以是var write=document.write<代码>文档。编写需要
文档
作为其上下文。如果不使用它,您将得到一个非法调用错误。对于自定义对象,正确的方法应该是什么。假设我们有一个对象名Car,函数是displayName。所以在这种情况下,我们可以写var originalDisplayName=carObj.displayName;这取决于调用函数的方式。如果
displayName
使用
carObj
作为上下文,则必须执行相同的
carObj.displayName.bind(carObj)
写入(文本)和写入.apply(此参数)之间的区别是什么