문제

Just a simple question :)

if I have :

var user = {'name': 'Fred'};

So

console.log(user.name); // Fred
console.log(user.age); // undefined

But

console.log(test); // ReferenceError: test is not defined

I don't understand why because for me it's the same as

console.log(window.test); // undefined

In my project, i try to check if a global variable exist but I have a referenceError... I don't really understand why the followinf code doesn't work...

if (TestGlobal) // ReferenceError: TestGlobal is not defined
   console.log(' allo 1 ');

if (typeof(TestGlobal ) !== 'undefined') // Ok
   console.log(' allo 1 ');
도움이 되었습니까?

해결책

…and a simple answer:

  • Property references always evaluate to their value or the undefined value if the key does not exist, as long as the base value is not undefined (then a TypeError would be thrown).
  • Variables throw ReferenceErrors if not defined before, unless they are used with the typeof keyword (where they just evaluate to "undefined").
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top