Reputation: 57
So I found this script online, and I understand all except for 2 parts:
1) var first = getUrlVars()["id"]; var second = getUrlVars()["page"];
I've never seen a function with brackets after it, what does it mean/do?
2) function(m,key,value)
Where are these parameters coming from (m, key, value)?
window.location would be: http://papermashup.com/index.php?id=123&page=home
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
var first = getUrlVars()["id"];
var second = getUrlVars()["page"];
alert(first);
alert(second);
Upvotes: 1
Views: 281
Reputation: 77454
The ()
are a method invocation.
The method returns a dictionary object (initialized as var vars = {}
). With vars["something"]
you do a dictionary lookup to retrieve data from the returned object.
You can rewrite ypur code to a faster version:
var dict = getUrlVars(); // Build dictionary (method invocation)
var first = dict["id"]; // Lookup
var second = dict["page"]; // Lookup
Shorter code is neither faster, nor more readable.
Upvotes: 0
Reputation: 1350
1) It's basically just chaining, you take advantage of knowing that getUrlVars will return an object, the brackets reference a property on the returned object.
2)Pretty similar logic. window.location.href returns a String, you chain the .replace() method.
function(m,key,value)
is the callback you pass to replace(), it's a standard JS method, you can see the docs (with the argument descriptions) here: String.prototype.replace()
Upvotes: 0
Reputation: 8683
var first = getUrlVars()["id"];
This line is calling the getUrlVars()
function, and then accessing the id
property of the return object and then setting the first
variable to the value of that property.
function(m,key,value)
is an anonymous function passed as a parameter to the replace
function on the String
object. Docs here. Essentially, it's passing a function into this parameter of the replace
function:
A function to be invoked to create the new substring (to put in place of the substring received from parameter #1). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.
Upvotes: 5