1

I want to override a function of an object such that its current functionality remains intact. See the following example:

Let say we want to log the text whenever the developer uses document.write something like:

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");

In above code the word America must be written to document and as well to the console. Is it possible? How it can be done?

asim-ishaq
  • 2,120
  • 5
  • 27
  • 52

1 Answers1

2

Cache the function first:

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");

Replacing native functions isn't good practice though, I would recommend against it, specially document.write, see here Why is document.write considered a "bad practice"?

Community
  • 1
  • 1
elclanrs
  • 85,039
  • 19
  • 126
  • 159
  • I can't understand the first line can it simply be var write =document.write; – asim-ishaq Jul 18 '14 at 21:03
  • `document.write` expects `document` as its context. Try without it, and you'll get an illegal invocation error. – elclanrs Jul 18 '14 at 21:07
  • What should be the right way in case of Custom objects. Let say we have an object name Car and the function is displayName. So In this case can we write var originalDisplayName = carObj.displayName; – asim-ishaq Jul 18 '14 at 21:11
  • It depends on how you call the function. If `displayName` uses `carObj` as context, the you would have to do the same `carObj.displayName.bind(carObj)` – elclanrs Jul 18 '14 at 21:12
  • What is the difference between write(text) and write.apply(this,arguments) – asim-ishaq Jul 18 '14 at 21:17
  • `apply` lets you call a function with a `this` value and an array of arguments. Check the MDN for more info https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply – elclanrs Jul 18 '14 at 21:20