I'm trying to learn about objects and JavaScript.
The problem I have is, it appears as if both the following do the same thing. My research shows nothing about what (if any) differences there are but this may be because it's very hard to question this within a search box.
Within the code, I've added comments to emphasise the differences
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id = "results"></div>
<script>
"use strict";
const results = document.getElementById("results");
const Thing = function(){ /* ****** THIS */
var _x;
this.set = function(x){
_x = x;
},
this.alert = function(){
results.innerHTML += _x + "<br />";
};
};
function Other(){ /* ****** AND THIS */
var _x;
this.set = function(x){
_x = x;
},
this.alert = function(){
results.innerHTML += _x + "<br />";
};
};
const t = new Thing();
t.set("b");
t.alert();
const t2 = new Thing();
t2.set("b2");
t2.alert();
t.alert();
t2.alert();
const o = new Other();
o.set("d");
o.alert();
const o2 = new Thing();
o2.set("d2");
o2.alert();
o.alert();
o2.alert();
</script>
</body>
</html>
What is the difference or are they both valid?
EDIT
I have seen the duplicate var functionName = function() {} vs function functionName() {}. The difference between the questions is I'm using the word new
. My question is, does that actually make a difference?