danp
danp

Reputation: 15241

How to override global functions in JavaScript, but keep a reference to the original function?

I'd like to implement a custom function for window.confirm, so I don't have to rewrite a large amount of legacy code, but be able to fallback to the original function if something goes wrong, or depending on some arbitrary logic.

A quick stub code, just for example (probably won't do it like this, but just for an idea):

window.confirm = function(message, successCallback){
  var ok = site.UI.confirmDialog(message);
  if (ok && typeof(successCallback) == 'function'){
      successCallback();
  } else {
     // maybe call original browser confirm?
     // window.confirmOriginal...?
  }
}

The question here is, how to get the original function if I'm overwriting it? Does it exist somewhere on the prototype, or am I looking at this all the wrong way?

Thanks.

Upvotes: 0

Views: 2580

Answers (1)

Joseph
Joseph

Reputation: 119847

Here's a demo

var origConfirm = window.confirm; //store for future use

​window.confirm = function(msg){   //override
     alert(msg);   
}

window.confirm('override!');      //should now be an alert
origConfirm('old confirm');       //the old confirm

Upvotes: 5

Related Questions