最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Is it possible to prototype on window or window.location? - Stack Overflow

programmeradmin0浏览0评论

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 badges
Add a ment  | 

3 Answers 3

Reset to default 3

You 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;
        }
发布评论

评论列表(0)

  1. 暂无评论