asim-ishaq
asim-ishaq

Reputation: 2220

JavaScript override an object method but keeping the original behavior intact

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?

Upvotes: 1

Views: 218

Answers (1)

elclanrs
elclanrs

Reputation: 94101

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"?

Upvotes: 2

Related Questions