我有以下 JavaScript 函数:
function Console() {
this.Log = function(msg) {
if (document.getElementById("console")) {
var console = document.getElementById("console");
console.innerHTML += msg + "<br/>";
}
}
}
问题一: 为什么要使用新的关键词?
new Console().Log("hello world");
为什么我不能这样做?
Console().Log("hello world without using new");
问题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
由于记录器末尾的 () ,这不会运行。
new logger().log("hello world");
我知道尾随 () 意味着该函数被立即调用,但为什么它不起作用?是不是因为 function() {} (); 不能赋值给其他变量?