One more confusion about closure , kindly help!

As i was suggested by some one in my earlier thread regarding closure confusion , when i was trying to increment the value of counter , i started reading YDKJS , now in an example here , i am a bit confused …

Now why do i need to use

var publicAPI = {
		login: doLogin
	};

	return publicAPI;

Why can i not just use

return doLogin() (as parameters are optional)

I tried but it does not work, but why ? Can any one please guide …


function User(){
	var username, password;

	function doLogin(user,pw) {
		username = user;
		password = pw;

		// do the rest of the login work
	}

	var publicAPI = {
		login: doLogin
	};

	return publicAPI;
}

// create a `User` module instance
var fred =  User();

fred.login( "fred", "12Battery34!" );

Because you have the parentheses next to the function name, you’re executing the doLogin function immediately. This isn’t what you want in a module. The whole point is to return references to the functions that you want to use later. Returning just the function name would work.

function User(){
	var username, password;

	function doLogin(user,pw) {
		username = user;
		password = pw;

		// do the rest of the login work
	}
        return doLogin; // don't use parentheses, just return the function reference
}

The point of having the publicAPI object is to group functionality related to the User object. If you have more than one function in User, then the only way to return references to all of them is in an object.

function User(){
	var username, password;

	function doLogin(user,pw) {
		username = user;
		password = pw;

		// do the rest of the login work
	}

        function doLogout() {
              // logout
        }

        function changeName(newName) {
               username = newName;
        }

	var publicAPI = {
		login: doLogin,
                logout: doLogout,
                changeName: changeName
	};

	return publicAPI;
}
3 Likes