Why doesn't my homemade isset function in javascript completely work?

Antonio Pavicevac-Ortiz

In a book trying to illustrate global/local variable scope it used this example to convey the concept:

test();

if (isset(bar)){ 

    alert('bar must be global!');

}else{

    alert('bar must be local!');

}

function test(){

   var foo = 3;
   bar = 5;

}


function isset(varname){

    return typeof varname != 'undefined';

}

Right now the if returns the alert 'bar must be global.', which makes sense because the variable passed to the isset(), bar, in this case is global. But why doesn't the if statement return the alert('foo must be local'); when you pass lets say when you pass foo in the isset function.

Roope Hakulinen

Since you haven't used the var keyword, the variable is defined on global scope and still exists after executing test function. This is explained more thoroughly here.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

Why doesn't my javascript regexp work with array items?

분류에서Dev

Why doesn't my SetLength work?

분류에서Dev

Why doesn't my iptables rule work?

분류에서Dev

Why doesn't my .desktop file work?

분류에서Dev

why the click() function doesn't work?

분류에서Dev

Chrome doesn't declare my JavaScript function

분류에서Dev

My New-RandomPassword function suddenly doesn't work

분류에서Dev

Why switch case in javascript doesn't work with string on Microsoft Edge?

분류에서Dev

JavaScript: location.replace doesn't work in the function

분류에서Dev

Why isEOF doesn't work?

분류에서Dev

Why json doesn´t work?

분류에서Dev

Why doesn't isdigit() work?

분류에서Dev

removeClass function doesn't work

분류에서Dev

jQuery function doesn't work

분류에서Dev

Why does my url reference in my test controller don't pass succesfully trought the if(isset)

분류에서Dev

My validation doesn't work for textarea

분류에서Dev

My button used to work -- but now it doesn't

분류에서Dev

`__call` doesn't work in my Lua code

분류에서Dev

Why when I use $(this) in a separate function and I call it inside a .each() it doesn't work?

분류에서Dev

parameter in function even not isset ,still work

분류에서Dev

Why is my javascript function not being invoked for simple MVC tutorial? Why can't I debug either?

분류에서Dev

Why doesn't LibreOffice work with the HUD?

분류에서Dev

Why wmctrl doesn't work for certain windows?

분류에서Dev

Why doesn't this math work with macros?

분류에서Dev

Why doesn't beep work in Ubuntu?

분류에서Dev

Why doesn't this simple enable_if work?

분류에서Dev

Why doesn't this Mongoose query work?

분류에서Dev

Why this jQuery doesn't work in Codeigniter?

분류에서Dev

Why doesn't source lib/* work?

Related 관련 기사

뜨겁다태그

보관