全部,说我们有如下代码.
var b ={};
var a=b;
b=null;
if (a==null)
{
alert('a is null');
}
Run Code Online (Sandbox Code Playgroud)
在代码运行之前,我曾认为a应该为null,因为我认为a并且b指向同一个对象或它们应该是相同的地址.但事实并非如此.javascript对象引用类型不是经典语言(c ++/c#/ java)吗?还是我错过了重要的事情?谢谢.
在JavaScript中,所有变量都按值保存并传递.
但是,在对象(任何不是原始对象)的情况下,该值是引用.
var v1, v2;
v1 = {
someProp: true
}; // Creates an object
v2 = v1; // The object now has two references pointed to it.
v1 = null; // The object now has one reference.
console.log(v2); // See the value of the object.
v2 = null; // No references left to the object. It can now be garbage collected.
Run Code Online (Sandbox Code Playgroud)