gpt4 book ai didi

javascript - 使用 var 或不使用 var 定义对象

转载 作者:行者123 更新时间:2023-11-30 12:49:17 25 4
gpt4 key购买 nike

var ninja = { 
yell: function(n){
return n > 0 ? ninja.yell(n-1) + "a" : "hiy";
}
};
console.log( ninja.yell(4) == "hiyaaaa", "A single object isn't too bad, either." );

var samurai = { yell: ninja.yell };
var ninja = null;

try {
samurai.yell(4);
} catch(e){
console.log( false, "Uh, this isn't good! Where'd ninja.yell go?" );
}

问题是 Var ninja=null

这是另一个对象吗?

还是和我第一行写的一样?

我猜这是另一个新对象,因为我用 var 定义了它?

但这是错误的,因为输出是错误的并且 catch body 跑了。这到底是什么?我也有与上面相同的示例,但它的工作方式不同,为什么?

var obj={name: "faizan", age:31}
var obj2 = obj;//obj2 pointing to the same memoray location of obj
console.log("before making null obj::",obj2.name);
console.log(obj==obj2,"::checking obj==obj2 while var obj2=obj");
obj=null; //obj became null
console.log("after making null obj::",obj2.name);//now this will need to be null but is working why??

最佳答案

变量只能在特定范围内声明一次。第二个 var ninja = null; 忽略了 var 声明,并简单地重新分配同一个变量,就像你写的 ninja = null; .

JS Lint将警告变量的重新声明。

关于javascript - 使用 var 或不使用 var 定义对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21521217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com