Search code examples
javascriptfunctionvariablesmethodsjavascript-objects

what is the difference between a function that returns an object with methods and a variable that is an object with methods


So I don't know a lot about best coding practices in JavaScript, but I'm hoping to better understand how functions should be designed to allow them to be called from outside the JavaScript file.

Take the following example. They both essentially do the same thing but one is stored in a variable and the other is a function.

var myVariable1 = {
	add1: function( that ){
		var number = parseInt( that.innerHTML, 10 );
		if( !isNaN( number )){
			document.getElementById( "variableResult" ).innerHTML = number + 1;
		}
	}
};
function myFunction(){
	var object = new Object();
	object.add1 = function( that ){
		var number = parseInt( that.innerHTML, 10 );
		if( !isNaN( number )){
			document.getElementById( "functionResult" ).innerHTML = number + 1;
		}
	}
	return object;
}
<!doctype html>
<html>
<head>
	<meta charset="utf-8">
	<title>Function or Variable</title>
	<script src="functionorvariable.js"></script>
</head>
<body>
	<main>
		<a onclick="myVariable1.add1( this )">4</a>
		<p id="variableResult"></p>
		<br>
		<br>
		<a onclick="window.myFunction().add1( this )">7</a>
		<p id="functionResult"></p>
	</main>
</body>
</html>

My question is what is the real difference here? Is it that they are the same just one may perform a little better than the other? Is one of them "better" than the other?

I'm just beginning to understand ways to accomplish modular design in JavaScript, so my apologies if both of these are bad practice.


Solution

  • myFunction creates an object and returns that everytime called. That makes little sense, as the object does not contain any properties, just a function that could just be a regular function.

    myVariable1 is just an object with a function property. It makes sense to group similar functions in one object to not pollute the global scope (and to keep things structured).