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

时间:2014-02-03 06:44:07

标签: javascript object

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定义它?

但是这是假的,因为out put是假的并且抓住了身体。到底是什么? 而且我也有像上面一样的例子,但这有什么不同的原因?

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??

1 个答案:

答案 0 :(得分:3)

变量只能在特定范围内声明一次。第二个var ninja = null;会忽略var声明,只需重新分配相同的变量,就像您编写ninja = null;一样。

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