I have the following JavaScript function:
function Console() {
this.Log = function(msg) {
if (document.getElementById("console")) {
var console = document.getElementById("console");
console.innerHTML += msg + "<br/>";
}
}
}
Question 1: Why do I need to use new key word?
new Console().Log("hello world");
Why couldn't I just do this?
Console().Log("hello world without using new");
Question 2:
var logger = function() {
this.log = function(msg) {
new Console().Log(msg);
new Console().Log("log initialized");
}
this.log2 = function(msg) {
new Console().Log(msg);
new Console().Log("log2 initialized");
}
}(); //notice the brackets
This wouldn't run because of the () at the end of logger.
new logger().log("hello world");
I know with the trailing () it means the function is called immediately but why wouldn’t it work? Is it because function() {} (); can't be assigned to other variables?