Please check this link for my complete code (It's simple though)
Question 1: What's the namespace defined in JavaScript? From my understanding, it looks like that any object can be an namespace?
Say we have a namespace called 'SPA', which means "Simple Page Application", inside this namespace, I define four module scope variables, $chatSlider, $toggleSlider, $onclickSlider, initModule;
var spa = (function( $ ) {
// Module scope variables
var
// Set constants
configMap = {
// some code here
},
// Declare all other module scope variables
$chatSlider, toggleSlider, onClickSlider, initModule;
toggleSlider = function() {
// some code here
}
// do not take action if slider is in transition
return false;
}
onClickSlider = function(event) {
toggleSlider();
return false;
}
// Public method / initModule/
// sets initial state and provides feature
initModule = function($container) {
// some code here
return true;
};
return {
initModule: initModule
};
})(jQuery);
And now I want to call initModule outside "spa", like this
$(document).ready(function () {
spa.initModule( $('#spa'));
});
Question 2: why we have to write
return {
initModule: initModule
};
To me, return {initModule} seems make more sense, what does the code above mean, what's the syntax of it?
Last but not least, usually I write function in the format like
function ( $var) {
// function code here
}
So what does this $ and jQuery mean here
function( $ ) {
}(jQuery)
What's the namespace defined in JavaScript?
Namespace isn't a piece of terminology defined by the language. It's common usage just means "An object, assigned to a global variable, to which all public functions for a piece of code are assigned so they can be exposed globally while only using a single global variable".
why we have to write
return {
etc etc
Otherwise the immediately invoked function expression (IIFE) will return undefined
. The return value is what is assigned to the global variable ( spa
).
You need it to be an object.
The left hand side of the :
is the property name, the right hand side is the value (which is the previously declared local variable which happens to have the same name as the property).
return {initModule}
seems make more sense
That's a syntax error in JavaScript. An object consists of a set of property/value pairs .
So what does this $ and jQuery mean here
$
is the name of the argument in the function expression definition.
jQuery
is the value passed as the first argument when that function is called (which is immediately).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.