Jump to content

JavaScript OOP problem

Featured Replies

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?

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

  • Author

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||""])
}
})();

Archived

This topic is now archived and is closed to further replies.

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.