使用var关键字定义一个obj而不使用 [英] define a obj with var keyword and without

查看:136
本文介绍了使用var关键字定义一个obj而不使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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?" ); 
}



现在samurai.yell(4)正在运行异常并且catch块正在运行。

现在看另一个示例这个


now samurai.yell(4) making exception and catch block is running.
Now look another expample this

var obj={name: "faizan", age:31}
    var obj2 = {name:obj.name};//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??



obj null now;但是obj2.name正在向我展示faizan。为什么??



上面的例子是samurai.yell(4);正在运行异常并且catch块正在运行。

我认为上面的示例没有区别b / w但是两个示例的行为都不相同为什么??


obj null now; but obj2.name is showing me faizan . why??
and
the above example working conversily samurai.yell(4); making exception and catch block is running.
I think no differece b/w above examples but the behaviour of both example are not same why??

推荐答案

在同一范围内, var 和非 - var 声明的变量不会有任何区别。变量是对象的容器。一旦你将一些不同的对象分配给一个变量(它可能是不同类型的对象),你就会失去对旧对象的访问权限,除非它被保存在其他地方。



这里解释 var 有所不同的情况:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var [ ^ ]。



当您在外部作用域中使用相同的变量名时,并在其声明下面的子作用域中使用相同的变量名时,会产生差异。然后同名可以被解释为与外部范围相同的变量,或者(带有var) - 重新引入的名称,与第一个无关。



-SA
In the same scope, var and non-var declared variable won't make any difference. A variable is the "container for an object". As soon as you assign some different object to a variable (it could be the object of different type), you loose the access to the old object, unless it was preserved somewhere else.

The cases where var makes some difference are explained here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var[^].

The difference is made when you use the same variable name in outer scope and, below its declaration, in sub-scope. Then the same name could be interpreted as the same variable as it was in the outer scope, or (with "var") — a reintroduced one, unrelated to the first one.

—SA


它是同一个对象。你只需将它设置为null。

对象按引用工作,因此在内存中指向相同的引用。
Its the same object. You just set it to null.
Objects work by reference and thus point to the same reference in memory.


这篇关于使用var关键字定义一个obj而不使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆