简体   繁体   English

javascript变量的不同行为

[英]Different behavior of javascript variables

I 've inspected different behavior for undefined/undeclared variables in javascript .For example : 我在javascript中检查了未定义/未声明变量的不同行为。例如:

var obj = {};
console.log(x);//Error
console.debug(obj.x) ;//undefined

My question is though c and obj.x both are not declared or defined then why I'm getting diff behavior? 我的问题是虽然c和obj.x都没有被声明或定义,但为什么我会得到差异行为? Am I missing something? 我错过了什么吗? How should I track which variable is already exist or not? 我该如何跟踪哪个变量已经存在?

This is expected behavior in javascript. 这是javascript中的预期行为。 If you are accessing an undeclared variable (x), an error occurs because engine doesn't know what you are trying to access. 如果您正在访问未声明的变量(x),则会发生错误,因为引擎不知道您要访问的内容。

On the other hand, objects have some sort of a dual nature. 另一方面,对象具有某种双重性质。 It acts as both an object and an array, and javascript allows you to try to access member of an array even if member under given key doesn't exist. 它既充当对象又充当数组,即使给定键下的成员不存在,javascript也允许您尝试访问数组的成员。 If there is no key under specified value, you will get back undefined . 如果指定值下没有键,则返回undefined Ie following two lines are equivalent 即以下两行是等效的

console.log(obj.x);

and

console.log(obj["x"]);

You would only get error if you try to access member of non existing variable. 如果您尝试访问非现有变量的成员,则只会出错。 Eg 例如

console.log(obj.x.x);

If you try to access an undefined variable, you will get an error, which is generally a good thing since it allows you to find bugs more easily. 如果您尝试访问未定义的变量,您将收到错误,这通常是一件好事,因为它允许您更容易地找到错误。

If you want to find out if a variable is defined or not, you can check its type like this: 如果要查明是否定义了变量,可以检查其类型如下:

console.info(typeof x === "undefined" ? "<undefined!>" : x);

In the case of obj.x , x is a property not a variable and you can always look up a property because of the dynamic nature of JavaScript objects. obj.x的情况下, x是属性而不是变量,并且由于JavaScript对象的动态特性,您始终可以查找属性。

You can't reference an undeclared variable without it being an error, unless you are assigning it in non-strict mode then it becomes an implicit global. 如果没有出现错误,则无法引用未声明的变量,除非您以非严格模式分配它,然后它将变为隐式全局变量。 Still error in strict mode though. 但在严格模式下仍然出错。

Trying to access object properties is not the same as trying to access variables, though you can access global variables from window : 尽管您可以从window访问全局变量,但尝试访问对象属性与尝试访问变量不同:

x; //referenceerror
window.x; //undefined, no reference error


You need to use window.x vs x in this situation for example: 在这种情况下,您需要使用window.x vs x ,例如:

var x = 5;

(function(){
    var x = 3;


    x === 3; //We cannot access the 5 
    window.x === 5 //Only window.x will do it here

})()​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM