1

I lack some fundamental understanding in function and variable declaration in javascript and am struggling to really understand it.

I have this function "urlParam" which I place in a general file ('reusable.js') to be reused:

(function (ko, $) {
    var urlParam = function (name, w) {
        w = w || window;
        var rx = new RegExp('[\&|\?]' + name + '=([^\&\#]+)'),
            val = w.location.search.match(rx);
        return !val ? '' : val[1];
    }
})(ko,jQuery);

Then I have a viewModel where I want to access this function, placed in a file 'viewmodel.js':

ViewModel = function(){
     var userId = urlParam("UserId");
};

In my view.html I include both files and then, after the html, I bind the view model to the view with:

ko.applyBindings(new ViewModel());

This cause an reference error: ReferenceError: urlParam is not defined

However if I place the urlParam-function outside the (function (ko, $) {})(ko, jQuery); declaration it works perfectly.

What does this (function () {})(); do really?

Shaunak D
  • 20,588
  • 10
  • 46
  • 79
Asle G
  • 568
  • 7
  • 27
  • 1
    Here's a good SO article: http://stackoverflow.com/questions/8228281/what-is-the-function-construct-in-javascript It's called an Immediately Invoking Function Expression. Basically you wrap an anonymous function in parentheses and then invoke it immediately. – WakeskaterX Apr 14 '15 at 12:04
  • it's an `anonymous` function executed when created – valar morghulis Apr 14 '15 at 12:06

2 Answers2

4

It's called an Immediately Invoking Function Expression.

What is the (function() { } )() construct in JavaScript?

The expression creates a new scope and has access to the parameters passed in through the outer parenthesis to the inner parenthesis, as well as any variables in the scope chain, however you have no way of accessing the variables within the function, as they are hidden within the scope of the function.

try something like this:

var urlParamVar = (function (ko, $) {
    var urlParam = function (name, w) {
        w = w || window;
        var rx = new RegExp('[\&|\?]' + name + '=([^\&\#]+)'),
            val = w.location.search.match(rx);
        return !val ? '' : val[1];
    }
    return urlParam;
})(ko,jQuery);

That way you are returning urlParam and setting that to the variable urlParamVar which will hold that function.

But that is not a very well structured way to do what you're trying to do.

Community
  • 1
  • 1
WakeskaterX
  • 1,408
  • 9
  • 21
1

you must try this without "var " to make a global function

(function (ko, $) {
  urlParam = function (name, w) {
    //.......
  }
})(ko,jQuery);
Jose Ricardo Bustos M.
  • 8,016
  • 6
  • 40
  • 62