使用var或不使用var定义对象 [英] defining an object with var or without var
问题描述
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
这是另一个对象吗?
还是和我在第一行写的一样?
or it same as i wrote it in first line?
我想这是另一个新对象,因为我用var定义它?
I guess it is another new object cause i define it with var?
但是这是假的,因为out put是false并且catch body运行了。到底是什么?
我也有与上面相同的例子,但这有什么不同的原因?
but this is false because out put is false and catch body ran. what the heck is this? and i also have the same example like above but this is working differently why?
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;
。
A variable can only be declared once in a particular scope. The second var ninja = null;
ignores the var
declaration, and simply reassigns the same variable, as if you'd written ninja = null;
.
JS Lint 将警告变量的重新声明。
JS Lint will warn about redeclarations of a variable.
这篇关于使用var或不使用var定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!