I want to write a query parsing method that would belong to the location class, but am not having any luck with
window.location.prototype
or
window.prototype
My goal is to do something along the lines of:
window.location.prototype.parseQuery = function(key){
//run a test on this.search to see if it contains key and return the val
}
Is window immutable? or am I just not referencing it correctly?
TIA
I want to write a query parsing method that would belong to the location class, but am not having any luck with
window.location.prototype
or
window.prototype
My goal is to do something along the lines of:
window.location.prototype.parseQuery = function(key){
//run a test on this.search to see if it contains key and return the val
}
Is window immutable? or am I just not referencing it correctly?
TIA
Share Improve this question asked Sep 22, 2012 at 7:12 Yevgeny SimkinYevgeny Simkin 28.5k41 gold badges145 silver badges243 bronze badges3 Answers
Reset to default 3You don't need the prototype when the object already exists and there's only one of them. You can just add a method directly to the object.
window.parseQuery = function() { /* your code here */};
or
window.location.parseQuery = function() { /* your code here */};
Also, the window
object is the global object in a browser so any global function is already a method on the window
object.
You should add the property directly on window.location
window.location.parseQuery = function(key){
//run a test on this.search to see if it contains key and return the val
}
prototype
is the property of Function, while window.location
is not a function.
Bah! should have run some more tests before asking...
The answer is Window.prototype
. Works in Chrome, haven't tested elsewhere yet.
as per the answers given, it would seem that there's no need to prototype on Window, given that it's a single global object. So here's my solution...
window.location.getQueryItem = function(key){
if(this.search.indexOf(key + "=") != -1){
reg = new RegExp(key + '=(.*?)(\&|$)', 'i');
return this.search.match(reg)[1];
}
return null;
}