BigMoosie Posted January 2, 2006 Posted January 2, 2006 I have a problem that I cannot solve, consider this: (function(){ var a = window.alert; window.alert=function(q){ a("BigMoosie\n\n"+q); } })(); This code will add the word 'BigMoosie' to every single alert called. This is quite neat as the workaround has been enclosed within an empty function making the variable 'a' inaccessible to global functions. I wish to do a similar thing to a prototype function for example this will make the split function's first argument defualt to an empty string if it is not set: String.prototype.split2 = String.prototype.split; String.prototype.split = function(s, a){ if (!s) s="" return this.split2(s, a); } However this is not as neat because the split2 function is global and can be accessed by other codes still, how would I make it private like in the previous example?
RyanJ Posted January 2, 2006 Posted January 2, 2006 However this is not as neat because the split2 function is global and can be accessed by other codes still' date=' how would I make it private like in the previous example?[/quote'] In Javascript prototypes are global like the objects they are prototypes of, the only way too solve this may be do define it within a function but that may not even work because the String object is still global. Cheers, Ryan Jones
BigMoosie Posted January 3, 2006 Author Posted January 3, 2006 Yeah that was exactly my problem, however I came up with a solution: (function(){ var j=String.prototype.split; String.prototype.split=function(q){ var temp=String.prototype.split; String.prototype.split=j; var result=this.split(q||''); String.prototype.split=temp; return result; } })(); Then I was alerted to the call and apply methods which is even better: (function(){ var j=String.prototype.split String.prototype.split=function(q){ return j.call(this,[q||""]) } })();
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now